2011-07-28, Thu

Adding custom options to Rail's select_tag

Three reasons why you’d want to do something like this:

  1. You want to hand code the of options for the select_tag
  2. You want to add a prompt to the top of the select_tag
  3. You want to manually append options to either the front or the end of the options generated by something like options_from_collection_for_select

The documentation says all you need to do is:

   <%= select_tag "gender", 
    "<option value=''>Gender</option>
     <option value='1'>Male</option>
     <option value='2'>Female</option>" 

but it would produce a blank drop-down select field with no options.

Thing is, Rails automatically escapes the string you provide in the second parameter for the select_tag method call, so the HTML tags get garbled up into HTML entities.

What you need to do is this:

   <%= select_tag "gender", 
     raw("<option value=''>Gender</option>
          <option value='1'>Male</option>
          <option value='2'>Female</option>") 

The raw method ensures that all the HTML tags stay intact and make their way to the browser.

Original solution found here

Isaac Su

tags: formtaghelper html options rails raw ruby select_tag



  1. The issue here is that it isn’t in every case simple to distinguish these obstacles and blockages. There are a few other research and concentrates done by different scientists, as per their experience they says that it is the cash convictions that keep us away from going for broke and starting our own business of land advancement Syria. The absolute most normal convictions are as under.

    marina gate select group · May 17, 04:59 AM · #