我对rails非常陌生,所以我的问题可能看起来很无趣。
我有HABTM自我联想。产品可以成为产品的“COMBO”,拥有N种产品。
class Product < ActiveRecord::Base
has_many :combo_elements, class_name: "ComboElement", foreign_key: :combo_id
has_many :element_combos, class_name: "ComboElement", foreign_key: :element_id
has_many :combos, :through => :element_combos
has_many :elements, :through => :combo_elements
accepts_nested_attributes_for :elements
end
class ComboElement < ActiveRecord::Base
belongs_to :combo, :class_name => 'Product'
belongs_to :element, :class_name => 'Product'
end
使用上面的代码,我可以列出组合的所有“元素”。此外,我可以列出产品所属的所有“组合”(ComboElement表有一个combo_id和一个element_id)
这是我的表格
<%= f.simple_fields_for :elements, @element do |b| %>
<%= b.input :element_id, :collection => Product.all.collect{ |t| [t.name, t.id ]}, selected: b.object.id %>
<%= b.link_to_remove "Remove this element" %>
<% end %>
我可以成功列出所有产品组合,但每当我尝试更新时,它都无法正常工作。
我的产品控制器具有以下代码
def product_params
params[:product].permit(:name, :price, elements_attributes: [:id, :element_id, :_destroy])
end
我感谢任何帮助。 提前谢谢!