每天一剂Rails良药之Keeping Track of Who Did What

今天我们看看怎样在数据库记录用户操作
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

BTW:昨天写的一篇博客《Processing Uploaded Images》不知道为什么在我的博客首页显示不了,但是通过search可以找到,蛙眼怎么出现这种白痴bug?

你可能感兴趣的:(cache,UP,ActiveRecord,Rails)