2011-10-05 51 views
0

背景:我在使用SinatraActiveRecord构建一个web应用程序,我很想利用acts_as_audited(根据https://github.com/collectiveidea/acts_as_audited)。 acts_as_audited的文档假设我将使用Rails,因此假设我将使用Rails来生成必要的迁移。我还没有找到使用acts_as_auditedSinatra的任何示例。任何使用sinatra与acts_as_audited的例子?

所以我的问题:有人能指出我在使用SinatraActiveRecordacts_as_audited的例子吗?

回答

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, '[email protected]') 
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 
+0

感谢本。我需要将什么迁移添加到我的表中才能支持此功能? –

+0

抱歉,关于延迟......以供参考,** audit_comment **存储在审计表中,因此,一旦您为** acts_as_audited **运行'rails g acts_as_audited:install'和'rake db:migrate',你应该很好走。 要获得'rails g acts_as_audited:install'的迁移代码,请查看github repo:https://github.com/collectiveidea/acts_as_audited/blob/master/lib/generators/acts_as_audited/templates/install .rb –

+0

所以我需要先安装导轨,我猜。 –