开发者

Is there a way to make a before_save conditional?

开发者 https://www.devze.com 2023-03-14 06:42 出处:网络
I am trying to make a before_save in a rails app conditional, but it doesn\'t seem to 开发者_如何学JAVAbe working.

I am trying to make a before_save in a rails app conditional, but it doesn't seem to 开发者_如何学JAVAbe working.

before_save method_call_to_run if self.related_model.some_method_that_returns_t_or_f?

If the 'some_method_that_returns_t_or_f' returns true, I want it to run the method before it saves the object otherwise I just want it to ignore the before_save.


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 reference, there's an excellent guide about this:

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


Rails 5

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

before_save do_something, if: :private_boolean_method?

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号