Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create nested objects using accepts_nested_attributes_for
    primarykey
    data
    text
    <p>I've upgraded to Rails 2.3.3 (from 2.1.x) and I'm trying to figure out the <code>accepts_nested_attributes_for</code> method. I can use the method to update existing nested objects, but I can't use it to create new nested objects. Given the contrived example:</p> <pre><code>class Product &lt; ActiveRecord::Base has_many :notes accepts_nested_attributes_for :notes end class Note &lt; ActiveRecord::Base belongs_to :product validates_presence_of :product_id, :body end </code></pre> <p>If I try to create a new <code>Product</code>, with a nested <code>Note</code>, as follows:</p> <pre><code>params = {:name =&gt; 'Test', :notes_attributes =&gt; {'0' =&gt; {'body' =&gt; 'Body'}}} p = Product.new(params) p.save! </code></pre> <p>It fails validations with the message:</p> <pre><code>ActiveRecord::RecordInvalid: Validation failed: Notes product can't be blank </code></pre> <p>I understand why this is happening -- it's because of the <code>validates_presence_of :product_id</code> on the <code>Note</code> class, and because at the time of saving the new record, the <code>Product</code> object doesn't have an <code>id</code>. However, I don't want to remove this validation; I think it would be incorrect to remove it.</p> <p>I could also solve the problem by manually creating the <code>Product</code> first, and then adding the <code>Note</code>, but that defeats the simplicity of <code>accepts_nested_attributes_for</code>.</p> <p>Is there a standard Rails way of creating nested objects on new records?</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.
 

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