我正在尝试将类别与产品相关联。
到目前为止我实现它的方式是
Class Product
has_many :categorizations
has_many :categories, through: :categorizations
.
Class Categorization
belongs_to :product
belongs_to :category
.
Class Category
has_many :categorizations
has_many :products, through: :categorizations
在我的 products/_form.html.erb
<div class="field">
<%= f.label :category_id %><br />
<%= collection_check_boxes(:product, :category_id, Category.all, :id, :name) %>
</div>
我不确定如何正确执行此操作。
解决方案
更改:
:category_id
至 :category_ids
并设置强参数def product_params
params.require(:product).permit(:title, :description, :price, :category_ids => [])
end
最佳答案
由于关系是多对多的,因此给定的产品应该响应 category_ids
(复数),不是 category_id
(单数)。
关于ruby-on-rails - Rails 4 collection_check_boxes,通过 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25048254/