Ruby on Rails: How to use a local variable in a collection_select
Posted
by mmacaulay
on Stack Overflow
See other posts from Stack Overflow
or by mmacaulay
Published on 2010-04-20T15:06:12Z
Indexed on
2010/04/21
1:13 UTC
Read the original article
Hit count: 311
ruby-on-rails
|form-helpers
I have a partial view which I'm passing a local variable into:
<%= render :partial => "products/product_row", :locals => { :product => product } %>
These are rows in a table, and I want to have a <select> in each row for product categories:
<%= collection_select(:product, :category_id, @current_user.categories, :id, :name, options = {:prompt => "-- Select a category --"}, html_options = { :id => "", :class => "product_category" }) %>
(Note: the id => "" is there because collection_select tries to give all these select elements the same id.)
The problem is that I want to have product.category
be selected by default and this doesn't work unless I have an instance variable @product
. I can't do this in the controller because this is a collection of products. One way I was able to get around this was to have this line just before the collection_select:
<% @product = product %>
But this seems very hacky and would be a problem if I ever wanted to have an actual instance variable @product
in the controller. I guess one workaround would be to name this instance variable something more specific like @product_select_tmp in hopes of not interfering with anything that might be declared in the controller. This still seems very hacky though, and I'd prefer a cleaner solution.
Surely there must be a way to have collection_select use a local variable instead of an instance variable.
Note that I've tried a few different ways of calling collection_select with no success:
<%= collection_select(product, ...
<%= collection_select('product', ...
etc.
Any help greatly appreciated!
© Stack Overflow or respective owner