【问题标题】:Any examples of using Sinatra with acts_as_audited?将 Sinatra 与acts_as_audited 一起使用的任何示例?
【发布时间】:2011-12-01 03:07:30
【问题描述】:

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

所以我的问题:有人可以指出一个使用SinatraActiveRecordacts_as_audited 的示例吗?

【问题讨论】:

    标签: activerecord sinatra acts-as-audited


    【解决方案1】:

    我已经能够使用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
    

    【讨论】:

    • 谢谢本。我需要向我的表中添加哪些迁移来支持这一点?
    • 抱歉耽搁了...作为参考,audit_comment 存储在审计表中,所以一旦你为 运行 rails g acts_as_audited:installrake db:migrate act_as_audited,你应该很高兴。要获取 rails g acts_as_audited:install 生成的迁移代码,请查看 github 存储库:github.com/collectiveidea/acts_as_audited/blob/master/lib/…
    • 所以我想我需要先安装导轨。
    • 我特定的 Sinatra 项目正在使用 ActiveRecord 与模型交互,并且与 Rails 应用程序绑定到相同的数据库后端,但您可以在我上面链接的 git 存储库中看到实际的模型迁移代码和根据您的选择创建适当的表。既然您说您在 Sinatra 应用程序中使用 ActiveRecord,我假设您有能力从您的应用程序运行迁移。我引用的迁移只是使用acts_as_audited 所需的默认迁移,所以如果您创建了该表,那么您应该很高兴。
    • 酷。当我下周重新投入该项目时,我会试一试。欢呼和感谢。
    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多