检测 Rails 4 中 update_attributes 上是否仅更新了一个属性

Not*_*ere 2 ruby-on-rails updates update-attributes ruby-on-rails-4

我正在制作一个博客应用程序。我需要根据已更改的属性数量有两种不同的方法。本质上,如果仅发布日期发生变化,我会做一件事......即使发布日期和其他任何事情发生变化,我也会做另一件事。

posts_controller.rb

def special_update
  if #detect change of @post.publication_date only
    #do something
  elsif # @post changes besides publication_date
  elsif #no changes
  end
end
Run Code Online (Sandbox Code Playgroud)

cra*_*sky 5

解决此问题的一种方法是在模型中使用ActiveModel::Dirty提供的方法,该方法可用于所有 Rails 模型。特别是改变的方法很有帮助:

model.changed # returns an array of all attributes changed. 
Run Code Online (Sandbox Code Playgroud)

在您的 Post 模型中,您可以使用after_updatebefore_update回调方法来完成您的肮脏工作。

class Post < ActiveRecord::Base
  before_update :clever_method

  private 
  def clever_method
    if self.changed == ['publication_date'] 
      # do something 
    else 
      # do something else 
    end
  end
end
Run Code Online (Sandbox Code Playgroud)