Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
RubyonRails-before_操作,仅当一个属性被更改时才有条件_Ruby_Ruby On Rails 4_Model_Before Filter - Fatal编程技术网

RubyonRails-before_操作,仅当一个属性被更改时才有条件

RubyonRails-before_操作,仅当一个属性被更改时才有条件,ruby,ruby-on-rails-4,model,before-filter,Ruby,Ruby On Rails 4,Model,Before Filter,在我的应用程序中,我发布了带有属性的title和price等的Post模型 当标题发生变化时,我有两个在动作之前只运行而当价格发生变化时,另一个只运行 class Post < ActiveRecord::Base before_update :do_something_with_title before_update :do_something_with_price def do_something_with_title // my code for title

在我的应用程序中,我发布了带有属性的
title
price
等的
Post
模型

标题
发生变化时,我有两个
在动作之前
只运行而当
价格
发生变化时,另一个只运行

class Post < ActiveRecord::Base

  before_update :do_something_with_title
  before_update :do_something_with_price

  def do_something_with_title
    // my code for title here
  end

  def do_something_with_price?
    // my code for price here
  end
class Post
我知道我可以使用
changed?
并在操作之前给出
一个
如果:
条件,但这将在
post
中的任何属性发生更改时应用,而不仅仅是在
title
price
发生更改时

class Post < ActiveRecord::Base

  before_update :do_something_with_title
  before_update :do_something_with_price

  def do_something_with_title
    // my code for title here
  end

  def do_something_with_price?
    // my code for price here
  end

感谢您的帮助

您可以使用
标题更改?
价格更改?

class Post < ActiveRecord::Base    
  before_update :do_something_with_title, if: :title_changed?
  before_update :do_something_with_price, if: :price_changed?
end
class Post
您可以使用

class Post < ActiveRecord::Base    
  before_update :do_something_with_title, if: :title_changed?
  before_update :do_something_with_price, if: :price_changed?
  ...
end
class Post

class Post
谢谢@Mihai。我只有一个问题。弗雷德(其他答案)的答案和你的有什么不同?哪一个更有效和更好的实践?谢谢,只是措辞不同而已。现在我想起来了,我想我更喜欢
if:
的方式。谢谢@Miahi,你更喜欢
:用标题做某事,if::logo\u oriu title\u changed?
在更新{post | post.do\u title\u如果post.title\u changed?}之前,你不应该使用块只调用一个方法,这与更新之前的
相同:如果::title\u发生了更改,则使用\u title做些什么?
,如果要执行多个方法,则使用块是有意义的