title: Ruby on Rails: How to create associated models on the fly?
body: <p>I have the following models:</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
    belongs_to :brand
    belongs_to :model
    accepts_nested_attributes_for :brand, :model
    ...
  end
  
  class Brand &lt; ActiveRecord::Base
    has_many :products
    has_many :models
    ...
  end
  
  class Model &lt; ActiveRecord::Base
    has_many :products
    belongs_to :brand 
    accepts_nested_attributes_for :brand
    ...
  end
  </code></pre>
  
  <p>I have a problem to create a new product.</p>
  
  <p>Here is the relevant code in the controller:</p>
  
  <pre><code>class ProductsController &lt; ApplicationController
    ...
    def create
      @product = Product.new(params[:product])
      if @product.save ...     # Here is the error
    end
    ...
  end
  </code></pre>
  
  <p>When user adds a new brand and a new model, <code>params[:product]</code> contains the following:</p>
  
  <pre><code>"brand_attributes"=&gt;{"name"=&gt;"my_new_brand"}
  "model_attributes"=&gt;{"model_no"=&gt;"my_new_model"}
  </code></pre>
  
  <p>and I got the following error:</p>
  
  <pre><code>Mysql2::Error: Column 'brand_id' cannot be null: INSERT INTO `models` ...
  </code></pre>
  
  <p>because model has a foreign key <code>brand_id</code> which is not set. I can't set it because the brand (like the model) is created on the fly when the product is created. I don't want to create the brand before the product, because then I the product has errors, I will need to delete the created brand.</p>
  
  <p>Then I tried to change <code>params[:product]</code> like this:</p>
  
  <pre><code>"brand_attributes"=&gt;{"name"=&gt;"my_new_brand", 
                       "model_attributes"=&gt;{"model_no"=&gt;"my_new_model"}}
  </code></pre>
  
  <p>but I end up with this:</p>
  
  <pre><code>unknown attribute: model_attributes
  </code></pre>
  
  <p>What would be the proper way to handle this ?</p>