【问题标题】:Checking if an attribute changed after commit in Rails在 Rails 中提交后检查属性是否更改
【发布时间】:2015-04-25 12:10:06
【问题描述】:

我知道使用dirtychanged?before_commit 情况下或在保存模型之前很有用。模型保存后,previous_changes 给出更改。这是伟大的。但是,

如果看起来像这样,我如何检查控制器中的特定属性是否已更改

def update
 @item = Item.find(params[:id])
if @item.update_attributes(item_params)
 # horray
 # check if the :name changed, if so do something about it
else
 # d'oh
end
end

有没有比!@item.previous_changes[:name].nil?更好的方法

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord


    【解决方案1】:

    我不知道有没有更好的方法,但我会这样做:

    if @item.previous_changes.has_key?('name')
      # Name has been changed.
    end
    

    【讨论】:

      【解决方案2】:

      在 Rails 5 中你可以使用saved_change_to_attribute? 来检查具体的变化。

      【讨论】:

        猜你喜欢
        • 2011-06-30
        • 1970-01-01
        • 2013-06-14
        • 2014-02-17
        • 1970-01-01
        • 2021-12-25
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多