How to create an if statement callback for multiple changed fields in Ruby on Rails?

I would like to create a before_save that only starts if changes have been made to any (but not necessarily all) of the three fields (street, city, state). How do you do it? Thanks

user.rb

 class User before_save :run_test_method, :if => street_changed? ... end 
+4
source share
3 answers

Option 1

You can create a method such as:

 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? 

Please note that :ok_to_run_test_method? is a symbol. Not sure if it was a typo or not, but in your question are you actually calling the class street_changed? method street_changed? .

Second option

Modify your callbacks a 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 
+10
source

You can do this on one line using Proc :

 class User before_save :run_test_method, :if => Proc.new { |u| u.street_changed? || u.city_changed? || u.state_changed? } ... end 
+8
source

You can also use lambda :

 before_save :run_test_method, if: ->(u) {u.street_changed? || u.something_changed? || u.something_else_changed?} 
0
source

Source: https://habr.com/ru/post/1439728/


All Articles