Note that there are some explanatory texts on larger screens.

plurals
  1. POIs :on => :create valid for a before_save callback in Rails 3.2.3
    primarykey
    data
    text
    <p>As you know, <code>before_save</code> callbacks are executed prior to <code>before_create</code> callbacks.</p> <p>Therefore, some people have suggested that in would be better to use <code>before_save :method, :on =&gt; :create</code> instead of <code>before_create</code> so that the callback method is executed at the right time in relation to other callbacks (such as autosave callbacks). See, for example, this <a href="http://blog.pivotal.io/labs/labs/activerecord-callbacks-autosave-before-this-and-that-etc" rel="nofollow noreferrer">Pivotal Labs blog post</a>, and <a href="https://stackoverflow.com/a/6967362/1121817">this StackOverflow answer</a>.</p> <p>However, as far as I can tell, the <code>:on =&gt; :create</code> option does not achieve the desired effect on a <code>before_save</code> callback. In other words, the callback is executed for every save regardless of whether it is a create or not.</p> <p>The <code>:on =&gt; :create</code> option <em>does</em> appear to be valid for <code>before_validation</code> callbacks, though.</p> <p>Could someone confirm whether the <code>:on =&gt; :create</code> is supposed to work for a <code>before_save</code>? Did it work in previous versions of Rails and is now broken, or are the aforementioned links simply mistaken?</p> <p>Assuming <code>:on =&gt; :create</code> is not valid, is the following acceptable, and/or is there a better way?</p> <pre><code>before_save :callback_method, :if =&gt; :new_record? </code></pre> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload