Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Revised: I revised the answer to use before_create and building, not creating, the associated models. The ActiveRecord machinery then takes care of saving the associated models once the parent is saved. </p> <p>I even tested this code!</p> <pre><code># in your Room model... has_many :doors before_create :build_main_door private def build_main_door # Build main door instance. Will use default params. One param (:main) is # set explicitly. The foreign key to the owning Room model is set doors.build(:main =&gt; true) true # Always return true in callbacks as the normal 'continue' state end ####### has_one case: # in your Room model... has_one :door before_create :build_main_door private def build_main_door # Build main door instance. Will use default params. One param (:main) is # set explicitly. The foreign key to the owning Room model is set build_door(:main =&gt; true) true # Always return true in callbacks as the normal 'continue' state end </code></pre> <p>Added...</p> <p>The build method is added by the owning model's machinery by the has_many statement. Since the example uses has_many :doors (model name Door), the build call is doors.build</p> <p>See the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001316" rel="noreferrer">docs for has_many</a> and <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001317" rel="noreferrer">has_one</a> to see all of the additional methods that are added.</p> <pre><code># If the owning model has has_many :user_infos # note: use plural form # then use user_infos.build(...) # note: use plural form # If the owning model has has_one :user_info # note: use singular form # then use build_user_info(...) # note: different form of build is added by has_one since # has_one refers to a single object, not to an # array-like object (eg user_infos) that can be # augmented with a build method </code></pre> <p>Rails 2.x introduced the autosave option for associations. I don't think it applies to the above (I'm using default). <a href="http://www.neeraj.name/2010/08/09/autosave-option-in-rails.html" rel="noreferrer">Autosave testing results.</a></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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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