2

I have an after save callback:

after_save :do_an_expensive_task_on_basis_of_flag_value

I later realized that this is a very expensive task and it does not make sense to call it when the value of flag is not set(on create) OR value of flag is not updated on update.

So one thing , i can do is to replace it with:

after_create :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag.present?}
after_update :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag_changed?}

But i am looking for a one liner, with a proc such that this task is called only when Flag is set on create and flag is updated on update with :after_save.

Note: This is not correct way:

after_save :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| a.flag.present? or a.flag_changed?}

As it still calls callback on update , even when flag is not changed.

4

2 回答 2

4

a.flag_changed?适用于这两种情况。但就您的知识而言,您可以这样做:

after_save :do_an_expensive_task_on_basis_of_flag_value , :if => Proc.new {|a| (new_record? and a.flag.present?) or a.flag_changed?}
于 2013-10-29T14:15:43.803 回答
3

您的过程中的逻辑略有错误。如果标志存在,它将始终运行,无论它是否在此保存时被更改。

对你需要的逻辑来说肯定a.flag_changed?足够了吗?如果添加了标志,它将从(其默认值,可能为 nil)更改为(无论您将其设置为什么)。

于 2013-10-29T14:00:15.800 回答