Ruby on rails 创建一个基于:已通过多个关系的表单
我是ruby新手,我正在尝试创建一个表单,允许您向订单中添加项目。表单将需要为订单中的每个项目记录数量Ruby on rails 创建一个基于:已通过多个关系的表单,ruby-on-rails,many-to-many,nested-forms,nested-attributes,has-many-through,Ruby On Rails,Many To Many,Nested Forms,Nested Attributes,Has Many Through,我是ruby新手,我正在尝试创建一个表单,允许您向订单中添加项目。表单将需要为订单中的每个项目记录数量 class Order < ActiveRecord::Base belongs_to :restaurant has_many :selections has_many :items, :through =>:selections; end class Selection < ActiveRecord::Base belongs_to :order
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
订单/\u 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 %>
{:class=>'form horizontal'}do | f |%>
'控件标签'%>
'文本\字段'%>
'控件标签'%>
'文本\字段'%>
“btn btn主节点”%>
t(“helpers.links.cancel”),
课程顺序路径:class=>btn'>
当我尝试呈现页面时,出现以下错误:
undefined method `quantity' for
<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Selection:0x007ffa0287cd60>
未定义的方法“数量”
我意识到这可能是因为我还没有初始化任何选择,但我不完全确定应该如何/在哪里进行初始化。提交表单时,我希望创建一个订单,为每个非空数量进行选择
所以我的第一个问题是,我如何构造我的表单,这样我就可以为我知道的每一项取一个数量
我是否需要初始化订单控制器中的任何内容才能使其正常工作
你能给我一些建议或者给我一个教程,告诉我如何设置订单控制器的创建方法吗
编辑:
我在订单控制器和表单中添加了一些代码,因此当我呈现页面时,不再出现错误,但没有呈现任何“选择”字段。我通过一些日志记录和调试器确认我正确地“构建”了4个选择,因此我希望这些表单元素会显示出来
如果您有任何想法,我们将不胜感激。您是否缺少
accepts_nested_attributes_for :nested_class
在什么地方
还有,我必须做一些类似的事情
<%= form_for [@restaurant,@order] do |f| %>
...
<%= f.fields_for :selections, @order.selections do |ff| %>
...
<% end %>
...
<% end %>
...
...
...
@order.selections
是一个数组,您可能无法获取它的属性(可能是为一个模型选择定义的)。同时发布您的餐厅模式,以明确依赖关系。我添加了我的餐厅和菜单模式。为什么您的餐厅模式中没有订单数?@walali这可能是个错误。我为创建订单而进行的迁移有一个t:restaurant。但这似乎并没有引起我的问题。
<%= form_for [@restaurant,@order] do |f| %>
...
<%= f.fields_for :selections, @order.selections do |ff| %>
...
<% end %>
...
<% end %>