开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜