我正在尝试创建一个订单表单,该表单还可以作为所有可用产品的列表。我有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_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(带有名称和其他属性),如果定义了数量,就会保存该列表。感谢您的帮助!
只需为每个供应添加一个order_item。取而代之的是:
@supplies.count.times { @order.order_lines.build }
这样做:
@supplies.each { |supply| @order.order_lines.build(supply: supply) }
然后在您的订单中,您不需要collection_select作为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。