AlexNikolaev94
AlexNikolaev94

Reputation: 1209

Populate the select tag with models that another model belongs to

I've got two models - Product and ProductCategory. Product belongs to ProductCategory, and product category can have many products as well. Now I'm trying to make a select tag in the form for creating a new Product, where I would pick a category and set this new product to belong to that category, but I'm confused a lot how to do that. In my controller I have

def create
    @product = Product.new(product_params)
    @product.save
    redirect_to products_path
end

private

def product_params
    params.require(:product).permit(:name, :description, :price, :product_category_id)
end

And in my view I tried to do something like this:

<%= form_for @product do |f| %>
    <%= f.collection_select :product_category_ids, ProductCategory.all, :id, :name, 
                                                          {multiple: true} %>
<% end %>

But I've got the following error

undefined method `product_category_ids' for #<Product:0x007f4982afa758>

How should I make this select tag to work?

ADDED

I've also tried to make in such a way:

<%= f.select :product_category_id, ProductCategory.all.collect { |c| [c.name, c.id] }, include_blank: true %>

But it returned me just an emptry option tag.

Upvotes: 0

Views: 55

Answers (1)

Raj
Raj

Reputation: 980

Just Try this:

product_category_ids is not the column of product model

<%= form_for @product do |f| %>
    <%= f.collection_select :product_category_id, ProductCategory.all, :id, :name, 
                                                          {multiple: true} %>
<% end %>

Upvotes: 1

Related Questions