views:

13

answers:

1

Hello, I have Category and a Product models. I want for each product to belong to a category. How would I have a drop down list so that you can select a category from the product pages?

I've gotten everything to work with this:

<%= collection_select(:category, :id, @categories, :id, :title, options ={:prompt => "-Select a category"}, :class =>"category") %>

and using

@product.category_id = params[:category][:id]

in my update/create controller methods

but it feels clunky and it does not "read" the value from the @product when editing and I have no idea how to make it so that it does. Am I doing something wrong?

+1  A: 

First two params for collection_select should be model you are trying to update and its attribute. So do something like this:

<%= collection_select(:product, :category_id, @categories, :id, :title, options ={:prompt => "-Select a category"}, :class =>"category") %>

This will update @product.category_id (so you don't have to do it manually) and it will also read correctly previously selected value.

Slobodan Kovacevic