【发布时间】:2014-07-13 20:52:15
【问题描述】:
我是 ruby 新手,我正在尝试整理一个表单,让您可以将项目添加到订单中。该表格将需要为订单中的每个项目计算一个数量。
class Order < ActiveRecord::Base
belongs_to :restaurant
has_many :selections
has_many :items, :through =>:selections;
end
class Selection < ActiveRecord::Base
belongs_to :order
belongs_to :item
end
class Item < ActiveRecord::Base
belongs_to :menu
has_many :selections
has_many :orders, :through => :selections
end
class Restaurant < ActiveRecord::Base
has_many :orders
has_many :menus
has_many :items, :through => :menus
end
class Menu < ActiveRecord::Base
belongs_to :restaurant
has_many :items
end
订单控制器
# GET /orders/new
def new
@order = Order.new
@restaurant.items.all.each do |item|
@order.selections.build
end
end
orders/_form.html.erb:
该表单应该列出可用的项目并允许您输入项目的数量。
<%= form_for [@restaurant,@order], :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :current_table, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :current_table, :class => 'text_field' %>
</div>
</div>
<% f.fields_for :selections do |ff| %>
<div class="control-group">
<%= ff.label :quantity, :class => 'control-label' %>
<div class="controls">
<%= ff.text_field :quantity, :class => 'text_field' %>
</div>
</div>
<% end%>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
course_orders_path, :class => 'btn' %>
</div>
<% end %>
当我尝试渲染页面时,出现以下错误:
undefined method `quantity' for
<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Selection:0x007ffa0287cd60>
我意识到这可能是因为我没有初始化任何选择,但我不完全确定我应该如何/在哪里做。提交表单后,我想创建一个订单,其中包含每个非空数量的选择。
所以我的第一个问题是如何构造我的表单,以便我可以为我所知道的每个项目取一个数量?
我是否需要在订单控制器中初始化任何内容才能使其正常工作?
您能给我任何建议或指向一个教程,告诉我如何设置订单控制器的创建方法吗?
编辑:
我向 Order 控制器和表单添加了一些代码,因此当我呈现页面时,我不再收到错误消息,但我的“选择”字段都没有呈现。我通过一些日志记录和调试器确认我正确地“构建”了 4 个选择,所以我希望这些表单元素会出现。
任何想法都将不胜感激。
【问题讨论】:
-
@order.selections是一个数组,您可能无法获得它的属性(可能是为一个模型定义的 - 选择)。还要发布您的餐厅模型以明确依赖关系。 -
我添加了我的餐厅和菜单模型。
-
为什么你的餐厅模型中没有
has_many :orders? -
@WaliAli 这可能是个错误。我创建订单的迁移有一个 t.belongs to :restaurant。不过,这似乎并没有引起我的问题。
标签: ruby-on-rails many-to-many nested-forms nested-attributes has-many-through