Activity history with Rails audited gem
Asked Answered
B

3

5

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?

Brion answered 12/6, 2012 at 10:44 Comment(0)
L
6

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

Levine answered 12/6, 2012 at 11:7 Comment(1)
Can be shortened to: Audited.audit_class.where("created_at >= ?", Date.today)Shively
S
4

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) }
Shively answered 30/12, 2015 at 7:23 Comment(0)
I
1

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)
Imf answered 19/6, 2012 at 14:53 Comment(1)
can someone help me with the views? i don't know how to show it in my views. i'm using rails 3.2.6 with the latest activerecord audited gem.Whited

© 2022 - 2024 — McMap. All rights reserved.