Creating Drop Down List Boxes the Rails way

Call them what you want Drop down list boxes, list boxes, combo boxes the list goes on. You know the ones I'm talking about, the rectangle looking things on a web page when selected give you a list of items you must pick from.

Whatever language you use, if they are on a web page chances are they will consist of a <select> tag with a few more <option> tags (the actual items) nested within them.

Coming from a Java/J2EE background amongst others and moving to I've seen my fair share of such boxes, in the latter you don't really have to think about creating the controls yourself it was drag and drop then wiring it up in the code behind.

Recently I have been playing around with Ruby on Rails, if you are new to ROR good place to start is of course watch the screen cast by David Heinemeier (I can never spell his last name) highly recommended.

After going though some tutorials, I created my first app Woohoo!. You guessed it a task list/to do list you were thing Hello World right?, the thing was I didn't know how to create and bind it to a data source. I quickly searched for some code. It turned out I was looking for the wrong thing, I was looking for a Drop Down List Box or ComboBox when I should have been searching for a Select list box "select" being the keyword.

Anyway hopefully this will come up next time someone from the world looks for something that exist in both worlds but is referred to by different names.

I finally found something in the documentation, below is one of several ways to create a drop down list box or is it a select box?

<%= select("task", "team_member_id", TeamMember.find(:all).collect {|p| [, ] }, {:prompt => 'Select'}) %>

Pretty simple, lets run though the code to better understand what is what

  • task, being the name of the model this select box is related to

  • team_member_id is the name of the id field in your object, I just think of it as the field name in my table

  • TeamMember being the object, what the find is doing is selection all the records from what some of you may refer to as a look up table

  • If there is no team_member_id then the :prompt => 'Select' sets this as the selected item with a text value of 'Select'

  •, is the name of your object attributes or field names of your look up table, for those guys text and value

Not that hard when you think about it.

Google is a good information resource, but if your don't ask the right questions then you won't get the right results!