我有一个产品表和一个相关的产品表,以一种方式进行相关工作:
Product(id: int, name: string)
RelatedProduct(id: int, product1: int, product2: int)
使用以下型号:
class Product < ActiveRecord::Base
validates :name, :uniqueness => true, :presence => true
has_many :relations, :class_name => "RelatedProducts", :foreign_key => :product1, inverse_of: :source
has_many :related_products, through: :relations, :source => :destination
end
class RelatedProducts < ActiveRecord::Base
belongs_to :source, :class_name => "Product", inverse_of: :relations
belongs_to :destination, :foreign_key => :product2, :class_name => "Product"
end
如果我预填充 RelatedProducts 表,这将有效,显示视图将正确显示所有相关产品。我无法弄清楚如何从 html 填充相关产品?
<%= form_for(@product) do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="related-products field">
<h3>Related Products</h3>
<%= f.collection_check_boxes :related_products, Product.where.not(id: @product.id), :self, :name %>
</div>
<div class="actions">
<%= f.submit 'Update Products' %>
</div>
<% end %>
强参数定义为:
params.require(:product).permit(:name, related_products: [:id, :name])