Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'll assume 2 things:</p> <ul> <li>That you are the <code>&lt;%= form_for @model_instance</code> idiom (explained on section 2.2 of <a href="http://guides.rubyonrails.org/form_helpers.html" rel="noreferrer">this guide</a>).</li> <li>That you want to store the "hot", "medium" and "cold" values as strings (not as numbers 1,2 and 3 or something similar) on your database.</li> </ul> <p>Let's say that you have two fields, called <code>:name</code> and <code>:temperature</code>, controlled by two <code>text_fields</code>: </p> <pre><code>&lt;% form_for @article do |f| %&gt; &lt;%= f.text_field :name %&gt; &lt;%= f.text_field :temperature %&gt; &lt;%= f.submit "Create" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>Now you want to change the :temperature control to a dropdown list, accepting hot, medium and cold as values. Then you can do that this way:</p> <pre><code>&lt;% form_for @article do |f| %&gt; &lt;%= f.text_field :name %&gt; &lt;%= f.collection_select :temperature, Article::TEMPERATURES, :to_s, :to_s, :include_blank =&gt; true %&gt; &lt;%= f.submit "Create" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>You will now have to define the <code>Article::TEMPERATURES</code> constant in your Article model. It shouldn't be very difficult:</p> <pre><code>class Article &lt; Activerecord::Base TEMPERATURES = ['hot', 'medium', 'cold'] </code></pre> <p>You may be wondering why I added the <code>:include_blank</code> part on the <code>collection_select</code>. This will add an "empty" option on your dropdown list. You will need that empty option when creating new objects, unless you want a "default" value to temperature.</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