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做些什么?
,如果要执行多个方法,则使用块是有意义的