Rails之记录用户操作数据库信息

阅读更多

db/migrate/002_add_audit_trails_table.rb

class AddAuditTrailsTable < ActiveRecord::Migration
  def self.up
    create_table :audit_trails do |t|
      t.column :record_id, :integer
      t.column :record_type, :string
      t.column :event, :string
      t.column :user_id, :integer
      t.column :created_at, :datetime
    end
end

  def self.down
    drop_table :audit_trails
  end
end
 

在app/models/audit_swpeeper.rb里

class AuditSweeper < ActionController::Caching::Sweeper    
  observe Person      
  def after_destroy(record)      
    log(record, "DESTROY")      
  end      
  def after_update(record)          
    log(record, "UPDATE")      
  end      
  def after_create(record)      
    log(record, "CREATE")      
  end      
  def log(record, event, user = controller.session[:user])          
    AuditTrail.create(:record_id => record.id,
                             :record_type => record.type.name,
                             :event => event,
                             :user_id => user)
  end
end
 

然后我们需要告诉PeopleController在操作Person对象时用audit_sweeper来记录操作

app/controllers/people_controller.rb

cache_sweeper :audit_sweeper
 

由于auditing机制依赖与Rails的缓存代码,所以确保config/environments/development.rb里将config.action_controller.perform_caching设置为true

 

from:http://www.sevenmike.com/page/9/

你可能感兴趣的:(Rails之记录用户操作数据库信息)