我正在尝试创建一个订单表单,该表单也可用作所有可用产品的列表。我有模型与has_many通过关联,我设法创建collection_select字段来创建连接模型上的记录工作正常,但我无法弄清楚如何构建显示每个产品的列表并接受连接记录的其他属性
我的模型(有点简化,我也有图像等):
class Supply < ActiveRecord::Base
attr_accessible :available, :name
has_many :order_lines
has_many :orders, through: :order_lines
accepts_nested_attributes_for :order_lines
end
class Order < ActiveRecord::Base
attr_accessible :month, :user_id, :order_lines_attributes
belongs_to :user
has_many :order_lines
has_many :supplies, through: :order_lines
accepts_nested_attributes_for :order_lines
end
class OrderLine < ActiveRecord::Base
attr_accessible :amount, :supply_id, :order_id
belongs_to :order
belongs_to :supply
validates_presence_of :amount
end
订单控制器:
def new
@order = Order.new
@supplies = Supply.available
@supplies.count.times { @order.order_lines.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @supply_order }
end
end
Order表单中的Order_line字段:
<%= f.fields_for :order_lines do |order_line| %>
<%= order_line.label :amount %>
<%= order_line.number_field :amount %>
<%= order_line.label :supply_id %>
<%= order_line.collection_select(:supply_id, @supplies, :id, :name) %>
<% end %>
代替这个我希望有一个列表,每个供应一个order_line(带有名称和其他属性),如果有定义的数量,它将被保存。任何帮助表示赞赏!
答案 0 :(得分:0)
只需为每个耗材添加order_item即可。而不是:
@supplies.count.times { @order.order_lines.build }
这样做:
@supplies.each { |supply| @order.order_lines.build(supply: supply) }
然后在您的订单中,您不需要supplier_select for supply_id,只需显示名称:
<%= order_line.object.supply.name %>
确保忽略空值的嵌套属性:
accepts_nested_attributes_for :order_lines, reject_if: proc { |attr| attr.amount.nil? || attr.amount.to_i == 0 }
您不需要Supply模型中的accepts_nested_attributes_for。