当前位置: 动力学知识库 > 问答 > 编程问答 >

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 :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?

网友答案:

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..

分享给朋友:
您可能感兴趣的文章:
随机阅读: