Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: How to use a local variable in a collection_select
    text
    copied!<p>I'm trying to create a &lt;select&gt; element using the collection_select method, but it seems that in order for the proper &lt;option&gt; 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).</p> <p>So when I create a &lt;select&gt; for the <code>categories</code> of a <code>product</code>, the proper category is NOT selected by default.</p> <p>_product_row.erb (DOES NOT WORK):</p> <pre><code>My product: &lt;%= product.name %&gt; &lt;%= collection_select(:product, :category_id, @current_user.categories, :id, :name, options = {:prompt =&gt; "-- Select a category --"}) %&gt; </code></pre> <p>Screenshot:</p> <p><a href="http://img534.imageshack.us/img534/8929/screenshot20100421at120.png" rel="nofollow noreferrer">alt text http://img534.imageshack.us/img534/8929/screenshot20100421at120.png</a></p> <p>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.</p> <p>_product_row.erb (WORKS):</p> <pre><code>&lt;% @product_select_tmp = product %&gt; &lt;%= collection_select(:product_select_tmp, :category_id, @current_user.categories, :id, :name, options = {:prompt =&gt; "-- Select a category --"}) %&gt; </code></pre> <p>Screenshot:</p> <p><a href="http://img534.imageshack.us/img534/1958/screenshot20100421at120l.png" rel="nofollow noreferrer">alt text http://img534.imageshack.us/img534/1958/screenshot20100421at120l.png</a></p> <p>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 <em>must</em> be a local variable in this partial).</p> <p>So how do I get collection_select to select the appropriate item when calling it with a local variable?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload