Is there a way to make a before_save conditional?

后端 未结 2 642
误落风尘
误落风尘 2021-02-06 22:40

I am trying to make a before_save in a rails app conditional, but it doesn\'t seem to be working.

before_save method_call_to_run if self.related_model.some_metho         


        
2条回答
  •  不要未来只要你来
    2021-02-06 23:16

    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" }
    

提交回复
热议问题