0

背景:我正在使用Sinatra并且ActiveRecord我很想利用acts_as_audited(根据https://github.com/collectiveidea/acts_as_audited)构建一个网络应用程序。acts_as_audited假设我将使用的文档Rails,因此假设我将使用它Rails来生成必要的迁移。我没有找到任何使用acts_as_auditedwith的例子Sinatra

所以我的问题是:有人可以指出一个使用Sinatraand ActiveRecordwith的例子acts_as_audited吗?

4

1 回答 1

2

我已经能够使用Audit.as_user方法让它工作。使用此方法可以让您审核记录,就好像更改是由您传入的用户对象所做的一样。

这是一个简单的例子。

# This is my User model, I want to audit email address changes to it.
class User < ActiveRecord::Base
  acts_as_audited
  # user has :email attribute
  ...
end

# This is what I would call in my Sinatra code.
# user is an instance of my User class
...
Audit.as_user(user) do
  user.audit_comment = "updating email from sinatra"
  user.update_attribute(:email, 'foo@bar.com')
end
...

一个更复杂的例子......

# Now I have a User model and a Comments model and I 
# want to audit when I create a comment from Sinatra
class User < ActiveRecord::Base
  has_many :comments
  acts_as_audited
  ...
end

class Comment < ActiveRecord::Base
  belongs_to :user
  acts_as_audited
  # has a :body attribute
  ...
end

# This is what I would call in my Sinatra code.
# Again, user is an instance of my User class
...
Audit.as_user(user) do
  user.comments.create(
    :body => "Body of Comment", 
    :audit_comment => "Creating Comment from Sinatra"
  )
end
于 2011-10-06T19:14:34.003 回答