× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Setting foreign key with has_one association

<p>Rails does a little magic with the has_one association.</p><p>Suppose you have a class Child that belongs_to Parent and you want to create a new Parent that has_one Child.  You might try something like this:</p><pre><code class="language-ruby">@parent = Parent.new @child = Child.first @child.update_attribute(:parent_id, @parent.id) @parent.save</code></pre><p>This will not work.  The reason is because @parent does not get assigned an id until after #save has been called.  Therefor, you are simply setting @child.parent_id to nil.  A better approach would be this:</p><pre><code class="language-ruby">@parent = Parent.new @parent.child = Child.first @parent.save</code></pre><p>This is more concise, and furthermore, it will only assign Child#parent_id if the Parent record successfully saves.</p><p>Furthermore, it should be noted that if you have a has_one association, Rails will enforce (without telling you) that your parent always has no more than 1 child.  For example, if @parent.child = Child.find(1), then you issue @parent.build_child, Rails will actually hit the database and clear the parent_id for the currently associated child record.</p>
comments powered by Disqus