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

前端 未结 3 1988
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题