我有一些模型的rails 3应用程序,如产品和用户。我正在使用"审核"gem 来跟踪产品的更改,它既简单又很好。
但是我想制作一个特殊的页面,我想在其中放置每日活动历史记录。第一步,我需要类似 Audits.all.order("created_at") 的东西,但没有这样的模型。
问题:如何获得所有型号今天的所有审核?
我认为您应该根据 gem 结构像Audited::Adapters::ActiveRecord::Audit.where("created_at >= ?", Date.today)
一样查询
能够通过以下方式访问今天的审核:
@audits = Audit.today
在app/models/
中创建一个audit.rb
文件,如下所示:
Audit = Audited.audit_class
class Audit
scope :today, -> do
where("created_at >= ?", Time.zone.today.midnight).reorder(:created_at)
end
end
审核还提供了一些可能有用的命名范围:
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) }
我的解决方案只是扩展审计对象,例如
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)