Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord Build or Create method requiring passing parent object in as argument
    primarykey
    data
    text
    <p>It was my understanding that the build/create method on child object within a model would automatically create the relationship.</p> <p>However, while I use a <code>validates</code> on both the parent and child object, I can't save the parent object, unless I explicitly pass in the parent object in the child build/create method</p> <p><strong>Parent Class</strong></p> <pre><code>class Order &lt; ActiveRecord::Base attr_accessible :tax, :total has_many :order_lines validates :user, presence: true validates :order_lines , presence: true end </code></pre> <p><strong>Child Class</strong></p> <pre><code>class OrderLine &lt; ActiveRecord::Base attr_accessible :order, :product, :qty belongs_to :order belongs_to :product ... ... validates :order, presence: true end </code></pre> <p><strong>PROBLEM</strong></p> <p>So I get errors if I try to:</p> <pre><code>order.order_lines.build(product: product) order.save =&gt; #error for order_lines, order can't be blank #or order.order_lines.create(product: product) =&gt; # throws same error </code></pre> <p>But I can do the following successfully:</p> <pre><code>order.order_lines.build(product: product, order: order) order.save =&gt; #true #or order.order_lines.create(product: product, order: order) =&gt; #true </code></pre> <p>This causes me further problems with FactoryGirl and creating tests.</p> <p>Am I wrong and misunderstanding that you have to explicitly pass in the parent object?</p> <p>Rails vs: 3.2.11</p> <p><a href="http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html" rel="nofollow">AR API documenation</a></p>
    singulars
    1. This table or related slice is empty.
    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. 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