I want to update multiple models with one form in rails. I have looked at Railscasts #196 and many nested model examples but can't get them to work. The difference is I want to create a record in the parent model in a form for the child model.
I have these 3 models:
User Model
has_many :products
has_many :stores
Product Model
belongs_to :user
belongs_to :store
accepts_nested_attributes_for :store
Store Model
has_many: products
I have a form where a user can enter a product in. I want it to have a field where they can enter the store as well. This entry will create a record in the store model as well as product model with the store_id stored in the store model.
Form
<%= form_for @product, :html => { :multipart => true } do |f| %>
<%= f.text_field :product_name %>
<% f.fields_for :store do |store|%>
<%= store.text_area :store_name %>
<%end%>
<% end %>
Controller
@product = Product.new
@product.store.build
This code results in the following error :
undefined method `build' for nil:NilClass
I just want to be able to create a new store entry as they enter the product. (if it is a duplicate entry I will not allow it, but I will handle that elsewhere). Any suggestions?