Ruby on Rails: How to create associated models on the fly ?
Posted
by
Misha Moroshko
on Stack Overflow
See other posts from Stack Overflow
or by Misha Moroshko
Published on 2010-12-30T00:26:14Z
Indexed on
2010/12/30
0:54 UTC
Read the original article
Hit count: 228
ruby-on-rails
|ruby-on-rails3
I have the following models:
class Product < ActiveRecord::Base
belongs_to :brand
belongs_to :model
accepts_nested_attributes_for :brand, :model
...
end
class Brand < ActiveRecord::Base
has_many :products
has_many :models
...
end
class Model < ActiveRecord::Base
has_many :products
belongs_to :brand
accepts_nested_attributes_for :brand
...
end
I have a problem to create a new product.
Here is the relevant code in the controller:
class ProductsController < ApplicationController
...
def create
@product = Product.new(params[:product])
if @product.save ... # Here is the error
end
...
end
When user adds a new brand and a new model, params[:product]
contains the following:
"brand_attributes"=>{"name"=>"my_new_brand"}
"model_attributes"=>{"model_no"=>"my_new_model"}
and I got the following error:
Mysql2::Error: Column 'brand_id' cannot be null: INSERT INTO `models` ...
because model has a foreign key brand_id
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.
Then I tried to change params[:product]
like this:
"brand_attributes"=>{"name"=>"my_new_brand",
"model_attributes"=>{"model_no"=>"my_new_model"}}
but I end up with this:
unknown attribute: model_attributes
What would be the proper way to handle this ?
© Stack Overflow or respective owner