2011-10-05 26 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

所以我需要先安裝導軌,我猜。 –

相關問題