RubyOnRails 自引用多对多

RubyOnRails self reference many to many

我有一个产品模型,我需要实现相关产品,所以我认为自我引用是最好的方法:

class Product < ActiveRecord::Base
  has_many :related_product_associations, class_name: "RelatedProduct"
  has_many :related_products, through: :related_product_associations, source: :related_product
end

class RelatedProduct < ActiveRecord::Base
    belongs_to :product
    belongs_to :related_product, class_name: "Product"
end

在products_controller中:

params.require(:product).permit(..., :related_products, ...)

问题: 1.我的models/controller还好吗 2.如何制作几个相关产品的表格。

我认为表格可能看起来像这样:

<%= f.collection_select :related_product, @products, :id, :name, include_blank: true %>
<%= f.collection_select :related_product, @products, :id, :name, include_blank: true %>
<%= f.collection_select :related_product, @products, :id, :name, include_blank: true %>

在products_controller中:

@products = Product.all
  1. 有没有一种方法可以使用 jQuery 嵌套表单实现类似茧的行为,以便我可以仅在需要时添加更多字段?

您的目标是以这种形式提交一组 ID related_product_ids=[1,2,3,4]

为此,参数必须命名为 product[realted_product_ids][]。不幸的是,你不能这样做。第二个参数必须是参数

# Note this doesn't work
<%= f.collection_select 'related_product_ids[]', @products, :id, :name, include_blank: true %> 

但是,你可以这样做(有多个)

<%= f.collection_select :related_product_ids, @products, :id, :name, {:selected => @product.related_product_ids, :include_blank => true}, {:multiple => true} %>

或者你可以这样做

<%- (1..4).each do |i| %>
  <%= select_tag 'product[related_product_ids][]', options_for_select(@products.map{|p| [p.name, p.id]}, @product.related_product_ids[i]), :include_blank => true %>
<% end %>

您也可以尝试使用复选框。稍后,切换到动态添加的下拉菜单应该不会太难。

<%- @products.each do |product| %>
  <%= check_box_tag 'product[related_product_ids][]', product.id, @product.related_product_ids.include?(product.id) %>
  <%= product.name %>
<%- end %>