有没有办法使 before_save 有条件? [英] Is there a way to make a before_save conditional?

查看:43
本文介绍了有没有办法使 before_save 有条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Rails 应用中有条件地创建 before_save,但它似乎不起作用.

before_save method_call_to_run if self.related_model.some_method_that_returns_t_or_f?

如果'some_method_that_returns_t_or_f'返回true,我希望它在保存对象之前运行该方法,否则我只希望它忽略before_save.

解决方案

你可以使用 :if

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

或者干脆

before_save do_something, :if =>some_condition

为了快速参考,这里有一个很好的指南:

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

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_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

这篇关于有没有办法使 before_save 有条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆