[ACCEPTED]-Is there a way to make a before_save conditional?-ruby

Accepted answer
Score: 63

you can use :if

before_save do_something, :if => Proc.new {|model| model.some_boolean_attr_or_method }

or simply

before_save do_something, :if => some_condition

EDIT:

for a quick 2 reference, there's an excellent guide about 1 this:

http://guides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks

Score: 15

Rails 5

I've had success defining a private method 5 which contains the boolean logic and then 4 passing it as a symbol (that last part seems 3 like a requirement):

before_save do_something, if: :private_boolean_method?

I also recently found 2 out you can simply pass a block (took me 1 a while to figure out the syntax):

before_save do_something, if: -> { condition == "met" }

More Related questions