I'm trying to create a <select> element using the collection_select method, but it seems that in order for the proper <option> to be selected, the identifier passed into collection_select needs to be an instance variable and not a local variable (this is happening in a partial).
So when I create a <select> for the categories
of a product
, the proper category is NOT selected by default.
_product_row.erb (DOES NOT WORK):
My product: <%= product.name %>
<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>
Screenshot:
I discovered that I was able to get it to work by declaring an instance variable before hand, but this seems like a huge hack to me.
_product_row.erb (WORKS):
<% @product_select_tmp = product %>
<%= collection_select(:product_select_tmp, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>
Screenshot:
Because this partial is iterating over a collection of products, I can't just have @product declared in the controller (IOW unless I'm missing something, product must be a local variable in this partial).
So how do I get collection_select to select the appropriate item when calling it with a local variable?