任何使用Sinatra和acts_as_audited的例子?

时间:2011-10-05 01:16:22

标签: activerecord sinatra acts-as-audited

背景:我正在使用SinatraActiveRecord构建网络应用,我希望利用acts_as_audited(根据https://github.com/collectiveidea/acts_as_audited })。 acts_as_audited的文档假定我将使用Rails,因此我假设我将使用Rails生成必要的迁移。我没有找到任何将acts_as_auditedSinatra一起使用的示例。

所以我的问题:有人可以指出我使用SinatraActiveRecord使用acts_as_audited的例子吗?

1 个答案:

答案 0 :(得分: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