【问题标题】:Rails 4 collection_check_boxes, with a has_many throughRails 4 collection_check_boxes,通过 has_many
【发布时间】:2014-09-22 18:28:23
【问题描述】:

我正在尝试将类别与产品相关联。 到目前为止我实现它的方式是

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

在我的产品/_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

【问题讨论】:

    标签: ruby-on-rails has-many-through checkboxlist categorization


    【解决方案1】:

    由于关系是多对多的,给定产品应该响应category_ids(复数),而不是category_id(单数)。

    【讨论】:

    • 谢谢你,这有效。我还必须设置def product_params params.require(:product).permit(:title, :description, :image_url, :price, :category_ids =&gt; []) end
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2014-12-16
    • 2013-11-24
    相关资源
    最近更新 更多