Multiple models, one form in rails. Want to create parent while creating the nested model object in a form
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 :storesProduct Model
belongs_to :user belongs_to :store accepts_nested_attributes_for :storeStore Model
has_many: productsI 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:NilClassI 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 han开发者_运维知识库dle that elsewhere). Any suggestions?
accepts_nested_attributes_for
Only works for the one to one and one to many relationships, where you have the primary model is the main parent.. You would use it in the the User model for products and/or stores. However it looks like you want to create a new store when they enter a product in if the store doesn't exist right?
Since it appears your store is just a field or two I would just add the store in the controller using the fields for it..
精彩评论