6

I'm trying to associate categories to products. The way I've implemented it so far is

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

and in my products/_form.html.erb

<div class="field">
<%= f.label :category_id %><br />
<%= collection_check_boxes(:product, :category_id, Category.all, :id, :name) %>
</div>

I'm not sure how to do this properly.

Solution
Change : :category_id to :category_ids and set the strong params

def product_params
  params.require(:product).permit(:title, :description, :price, :category_ids => [])
end
microspino
  • 7,693
  • 3
  • 48
  • 49
JacobJuul
  • 152
  • 1
  • 12

1 Answers1

7

Being that the relationship is many-to-many a given product should respond to category_ids (plural), not category_id (singular).

jparonson
  • 322
  • 1
  • 4
  • 1
    Thank you, this worked. I also had to set `def product_params params.require(:product).permit(:title, :description, :image_url, :price, :category_ids => []) end` – JacobJuul Jul 31 '14 at 08:32