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

---

Comment

Commenting is closed for this article.

---