My Rails option_tag

Posted by Kyle Heon Thu, 13 Jul 2006 20:31:00 GMT

Being relatively new to Ruby and Rails I’ve been taking it slow as I work through an application that I’m building, mostly for fun but has applicability when finished where I work.

Anyways, I have a series of multiple select boxes that exist on a particular form. In all my research online I wasn’t able to find a helper method that would handle multiple select boxes. Given that I decided to write a helper myself. At the moment this just writes out just the option tag and selects it if the value matches something found in a passed in collection.

Here is the helper code:

def option_tag(value, title, collection)
    begin
      if (!collection.empty? and collection.find(value))
        selected = " selected=\"selected\""
      end
    rescue
      selected = nil
    end
    "<option value=\"#{value}\"#{selected}>#{title}</option>"
  end

Here’s how to use it:

<p><label for="browser_id">Browsers</label><br />
  <select id="browser_id" name="browser[id][]" size="5" multiple="multiple">
    <% for browser in @browsers %>
      <%= option_tag(browser.id, browser.name, @item.browsers) %>
    <% end %>
  </select>
  </p>

I’ll probably look into building something that can handle a multiple select and reuse as much of the Rails helper methods as possible.

If I completely missed something and can actually do what I want using what Rails offers please let me know, I’d rather use what is there then roll my own unless I have a good reason to.

Also, should you see something glaringly wrong or inefficient in my code above please say so, as I said, I’m just learning Ruby and Rails and want to learn how to do things the right way.

Posted in  | Tags ,  | 1 comment | no trackbacks

Comments

  1. Scoots said 3 days later:

    Yo Kyle!

    Nice blog ya got going here… drop me a line sometime, was just chatting with Lonestar (who works for me now in an official capacity), and we were trying to remember the name of your gaming site…

Trackbacks

Use the following link to trackback from your own site:
http://www.kyleheon.com/articles/trackback/96

Comments are disabled