0
我有一個產品表和相關產品的表,相關工作的一種方式:填充自連接表中的Rails 4
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表,show view將正確顯示所有相關產品。我無法弄清楚如何從html中填充RelatedProducts?
<%= 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])
也許嘗試爲related_products模型製作form_for – amb110395