【问题标题】:Ruby on Rails - before_action with condition only when one attribute has been changedRuby on Rails - before_action 仅在一个属性已更改时具有条件
【发布时间】:2018-01-28 00:26:10
【问题描述】:

在我的应用程序中,我的 Post 模型具有 titleprice 等属性。

我有 2 个before_actions,我想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

我知道我可以使用changed? 并给before_action 一个if: 条件,但这将适用于post 中的任何属性发生变化的情况,而不仅仅是titleprice 发生变化的情况。

感谢任何帮助!

【问题讨论】:

    标签: ruby ruby-on-rails-4 model before-filter


    【解决方案1】:

    您可以使用title_changed?price_changed?

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

    【讨论】:

      【解决方案2】:

      你可以使用

      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 < ActiveRecord::Base    
        before_update { |post| post.do_something_with_title if post.title_changed? }
        before_update { |post| post.do_something_with_price if post.price_changed? }
        ...
      end
      

      【讨论】:

      • 谢谢@Mihai。我只有一个问题。 Frede(其他答案)的答案和你的有什么区别?哪一个更有效和更好的做法?谢谢
      • 只是措辞不同。现在想来,我想我更喜欢if:的方式。
      • 谢谢@Miahi,您更喜欢:do_something_with_title, if: :logo_ori_title_changed? 而不是before_update { |post| post.do_something_with_title if post.title_changed? }
      • 你不应该使用一个块来调用一个方法,它和before_update :do_something_with_title, if: :title_changed?一样,如果你想执行多个方法,使用一个块是有意义的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多