Fields_for 设置表单无法正确使用 Accepts_nested_attributes
我确信这只是我缺乏经验,所以请耐心等待。
我有一个带有价格的模型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要
fields_for :price
,而不是item.fields_for
以获得更完整的示例,请查看模式 此处
所有菜单项的价格都将为空值,除非您明确给它们一个可以在 before_save 回调中执行的操作(如果您这样做)选择了
you need
fields_for :price
, notitem.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