Ruby-on-rails 有没有办法使 before_save 有条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6409932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to make a before_save conditional?
提问by Darren
I am trying to make a before_save in a rails app conditional, but it doesn't seem to be working.
我正在尝试在 Rails 应用程序中有条件地进行 before_save,但它似乎不起作用。
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.
如果“some_method_that_returns_t_or_f”返回true,我希望它在保存对象之前运行该方法,否则我只希望它忽略before_save。
回答by Andrea Pavoni
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
http://guides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks
回答by sambecker
Rails 5
导轨 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" }

