我有一个产品模型,我需要实现相关产品,所以我想一个自我引用是做到这一点的最好办法:RubyOnRails自我引用多对多
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.我的车型/控制器是否正确 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
- 是否有实现茧般的行为方式与jQuery嵌套形式,所以我可以添加更多的领域,只有当我需要他们?
有关型号的命名 - 我会考虑调用连接表像related_product_association,因为这就是你把它的产品型号。 – Swards