多种型号,一种导轨形式。想要在表单中创建嵌套模型对象时创建父对象

发布于 2024-11-13 22:22:00 字数 874 浏览 2 评论 0原文

我想用 Rails 中的一种形式更新多个模型。我看过 Railscasts #196 和许多嵌套模型示例,但无法让它们工作。不同之处在于我想在子模型的表单中在父模型中创建记录。

我有这 3 个型号:
用户模型
has_many :产品
has_many :存储

产品模型
属于:用户
属于:商店
Accept_nested_attributes_for :store

商店模型
has_many:产品

我有一个表单,用户可以在其中输入产品。我希望它有一个字段,用户也可以在其中进入商店。此条目将在商店模型以及产品模型中创建一条记录,其中 store_id 存储在商店模型中。

表单

<%= 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 %>

控制器

    @product = Product.new
    @product.store.build

此代码会导致以下错误:
undefined method `build' for nil:NilClass

我只是希望能够在他们进入产品时创建一个新的商店条目。 (如果它是重复的条目,我将不允许它,但我会在其他地方处理)。有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自找没趣 2024-11-20 22:22:00

Accepts_nested_attributes_for

仅适用于一对一和一对多关系,其中主要模型是主要父级。
您可以在产品和/或商店的用户模型中使用它。但是,如果商店不存在,您似乎想在他们输入产品时创建一个新商店,对吧?

因为看起来您的商店只是一两个字段,所以我只需使用其字段将商店添加到控制器中。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文