How do you create a callback with an if statement for multiple changed fields in Ruby on Rails?

前端 未结 3 1984
小蘑菇
小蘑菇 2021-01-18 01:34

I would like to create a before_save callback that only gets run if there have been changes to any (but not necessarily all) of the three fields (street, city,

相关标签:
3条回答
  • 2021-01-18 02:19

    Option One

    You could create a method like:

    def ok_to_run_test_method?
      street_changed? || something_changed? || something_else_changed?
    end
    

    and then use:

    before_save :run_test_method, :if => :ok_to_run_test_method?
    

    Note how :ok_to_run_test_method? is a symbol. Not sure if it was a typo or not but in your question you are actually calling a class method street_changed?.

    Option Two

    Modernise your callbacks a little bit and use the block-style syntax:

    before_save do
      if street_changed? || something_changed? || something_else_changed?
        # whatever you currently have in #run_test_method
      end
    end
    
    0 讨论(0)
  • 2021-01-18 02:19

    You can do it in one line using a Proc:

    class User
      before_save :run_test_method, :if => Proc.new { |u| u.street_changed? || u.city_changed? || u.state_changed? }
    
      ...
    end
    
    0 讨论(0)
  • 2021-01-18 02:30

    You can also use a lambda:

    before_save :run_test_method, if: ->(u) {u.street_changed? || u.something_changed? || u.something_else_changed?}
    
    0 讨论(0)
提交回复
热议问题