Ruby on Rails: How to use a local variable in a collection_select
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, :categor开发者_C百科y_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}) %>
Screenshot:
alt text http://img534.imageshack.us/img534/8929/screenshot20100421at120.png
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:
alt text http://img534.imageshack.us/img534/1958/screenshot20100421at120l.png
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?
Have you tried passing in the :selected
key in the options hash? If you provide it with the current product.id
it should behave the way you're expecting.
<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, {:prompt => "-- Select a category --", :selected => product.category.id}) %>
You can pass collections to partials and designate a local variable to pass them as:
<%= render :partial => "products/product_row", :collection => @products, :as => :products %>
Relevant documentation: http://apidock.com/rails/ActionView/Partials
精彩评论