Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity history with Rails audited gem

I have rails 3 application with some models, like Product and User. I'm using "audited" gem to track changes for products, it's simple and nice working.

But I want to make special page where I want to put daily activity history. I need something like Audits.all.order("created_at") for first step, but there is no such model.

Question: How can I get all audits for today for all models?

like image 687
Alve Avatar asked Jun 12 '12 10:06

Alve


3 Answers

I think you should query like Audited::Adapters::ActiveRecord::Audit.where("created_at >= ?", Date.today) according to the gem structure

like image 192
Sergey Kishenin Avatar answered Nov 11 '22 09:11

Sergey Kishenin


To be able to access today's audits with:

@audits = Audit.today

Create an audit.rb file in app/models/ like:

Audit = Audited.audit_class

class Audit
  scope :today, -> do
    where("created_at >= ?", Time.zone.today.midnight).reorder(:created_at)
  end
end

Audited also provides a few named scopes of its own that may prove useful:

scope :descending,    ->{ reorder("version DESC") }
scope :creates,       ->{ where({:action => 'create'}) }
scope :updates,       ->{ where({:action => 'update'}) }
scope :destroys,      ->{ where({:action => 'destroy'}) }

scope :up_until,      ->(date_or_time){ where("created_at <= ?", date_or_time) }
scope :from_version,  ->(version){ where(['version >= ?', version]) }
scope :to_version,    ->(version){ where(['version <= ?', version]) }
scope :auditable_finder, ->(auditable_id, auditable_type){ where(auditable_id: auditable_id, auditable_type: auditable_type) }
like image 24
Eliot Sykes Avatar answered Nov 11 '22 09:11

Eliot Sykes


my solution is simply to extend the audit object, e.g.

cat lib/audit_extensions.rb
# The audit class is part of audited plugin
# we reopen here to add search functionality
require 'audited'

module AuditExtentions
  def self.included(base)
    base.send :include, InstanceMethods
    base.class_eval do
      belongs_to :search_users, :class_name => 'User', :foreign_key => :user_id
      scoped_search :on => :username, :complete_value => true
      scoped_search :on => :audited_changes, :rename => 'changes'
      scoped_search :on => :created_at, :complete_value => true, :rename => :time, :default_order => :desc
      scoped_search :on => :action, :complete_value => { :create => 'create', :update => 'update', :delete => 'destroy' }
      before_save :ensure_username

    end
  end

  module InstanceMethods
    private

    def ensure_username
      self.username ||= User.current.to_s rescue ""
    end

  end
end

Audit = Audited.audit_class
Audit.send(:include, AuditExtentions)
like image 1
Ohad Levy Avatar answered Nov 11 '22 08:11

Ohad Levy