fields_for和has_many通过

时间:2012-03-20 10:52:03

标签: ruby-on-rails has-many-through fields-for

我有这些模特:

class Order < ActiveRecord::Base
  has_many :order_lines
  has_many :prizes, :through => :order_lines
  accepts_nested_attributes_for :order_lines
end

class Prize < ActiveRecord::Base
  has_many :order_lines  
end

class OrderLine < ActiveRecord::Base
  belongs_to :order
  belongs_to :prize
end

我希望订单中的嵌套表单显示每个奖品旁边有一个文本框,用户可以在其中输入部分(例如订购金额)。提交表单时,create action应相应地创建order_lines。我无法在任何地方找到解决方案。

1 个答案:

答案 0 :(得分:0)

首先,在订单模型中使用accepts_nested_attributes_for :prizes,而不是您拥有的。

之后很容易,只需在视图中添加一个表单(没有额外的步骤控制器)

<%= form_for @order do |order_form| %>
  ..
  <%= order_form.fields_for :prizes do |prizes_form| %>
    <%= prizes_form.text_field :piece %>
    ..
  <% end %>
 ..
<% end %>

直接来自文档...... You should definitely check that first