As you know, before_save
callbacks are executed prior to before_create
callbacks.
Therefore, some people have suggested that in would be better to use before_save :method, :on => :create
instead of before_create
so that the callback method is executed at the right time in relation to other callbacks (such as autosave callbacks). See, for example, this Pivotal Labs blog post, and this StackOverflow answer.
However, as far as I can tell, the :on => :create
option does not achieve the desired effect on a before_save
callback. In other words, the callback is executed for every save regardless of whether it is a create or not.
The :on => :create
option does appear to be valid for before_validation
callbacks, though.
Could someone confirm whether the :on => :create
is supposed to work for a before_save
? Did it work in previous versions of Rails and is now broken, or are the aforementioned links simply mistaken?
Assuming :on => :create
is not valid, is the following acceptable, and/or is there a better way?
before_save :callback_method, :if => :new_record?
Thank you.
You're right, there is no
:on
option forbefore_save
callback. But, I don't understand, why usebefore_save
instead ofbefore_create
.before_create
callback will be called right afterbefore_save
.Of course, you can use
before_save :callback_method, :if => :new_record?
. But I personally don't like this solution - what if I need to add conditions in the:if
option?If one have a dependency between
before_save
andbefore_create
callbacks, I`d suggest, to combine 2 callbacks. For instance (pseudocode):