Fields_for 设置表单无法正确使用 Accepts_nested_attributes

发布于 2024-12-08 00:53:56 字数 1172 浏览 1 评论 0原文

我确信这只是我缺乏经验,所以请耐心等待。

我有一个带有价格的模型 MenuItem。不同的项目类型(菜单项、产品、活动)可以有价格。

我的设置如下:

class MenuItem < ActiveRecord::Base
   ...
   has_one :price, :as => :pricable
   accepts_nested_attributes_for :price
   attr_accessible :price_attributes
   ...
end

class Price < ActiveRecord::Base
   belongs_to :pricable, :polymorphic => true
end

Price 对象有一个价格值,在 Mysql5 上是小数(8,2)。

在我的形式中:

<%= form_tag "/menus/save" do %>
...
<% menu_header_form.menu_items.each do |item| %>
   <div><%=item['header'] %></div>
   <%=text_field :menu_item, :header, :index=>item.id, :value=>item.header %>
   <%=text_field :menu_item, :sort, :index=>item.id, :value=>item.sort, :size => 2 %>
   <% item.fields_for :price do |menu_item_price| %>
        <%= menu_item_price.text_field :price %>
   <% end %>

<% end %>

并收到以下错误:

undefined method `fields_for' for #<MenuItem:0x007fec8d9be138> 

我将如何迭代以获得价格值?我的模型的设置方式是否意味着这些 menu_items 默认情况下会有与其关联的价格记录(甚至是空/空值)?

谢谢

I'm sure that this is just a lack of experience on my part so bear with me.

I have a model MenuItem that has a Price. Different item types (menu_items, products, events) can have prices.

I have set it up as follows:

class MenuItem < ActiveRecord::Base
   ...
   has_one :price, :as => :pricable
   accepts_nested_attributes_for :price
   attr_accessible :price_attributes
   ...
end

class Price < ActiveRecord::Base
   belongs_to :pricable, :polymorphic => true
end

The Price object has a price value which is a decimal(8,2) on Mysql5.

In my form:

<%= form_tag "/menus/save" do %>
...
<% menu_header_form.menu_items.each do |item| %>
   <div><%=item['header'] %></div>
   <%=text_field :menu_item, :header, :index=>item.id, :value=>item.header %>
   <%=text_field :menu_item, :sort, :index=>item.id, :value=>item.sort, :size => 2 %>
   <% item.fields_for :price do |menu_item_price| %>
        <%= menu_item_price.text_field :price %>
   <% end %>

<% end %>

and am getting the following error:

undefined method `fields_for' for #<MenuItem:0x007fec8d9be138> 

How would I iterate through to get the price value? Would the way that my models are set up mean that those menu_items would have a price record associated with them by default(even empty / null values)?

thx

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

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

发布评论

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

评论(1

单身情人 2024-12-15 00:53:56

您需要 fields_for :price ,而不是 item.fields_for

以获得更完整的示例,请查看模式 此处

所有菜单项的价格都将为空值,除非您明确给它们一个可以在 before_save 回调中执行的操作(如果您这样做)选择了

you need fields_for :price , not item.fields_for

for a more complete example, take a look at the pattern here

All menu items would have a null value for price unless you explicitly give them one which you could do in a before_save callback if you chose

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