About these ads

David Vassallo's Blog

If at first you don't succeed; call it version 1.0

Rails : of select_tags and options_from_collection_for_select


A bit difficult to get this information… Rails’ helper when building select elements for a form is the well-known select_tag. If you are populating the options within a select form with data from your database through a model, you would use the options_from_collection_for_select helper. An example  is in fact quite straightforward:

options_from_collection_for_select(@extensions, 'ext', 'name')

Meaning if your controller has populated the collection “@extensions” using methods such as find, where, etc… the helper will then create a select element using the ‘ext’ field as a value, and the ‘name’ field as text to display in the web form, like so:

Selection_173

But, what if you would like to display a different format to the user in the web form? Something like “name (ext)”, where name and ext are to be populated from the database. Simply using

options_from_collection_for_select(@extensions, ‘ext’, ‘user(ext)’)

will result in an error of course:

Selection_172

 

But the error “undefined method ‘user(ext)’ for #Users gives an important clue. Users happens to be my model class. So it seems rails is looking for a method called user(ext) within the model class. Let’s add a method to the models/users.rb file:

class Users < ActiveRecord::Base

def userExt
self.user + ” (” + self.ext.to_s + “)”
end

end

The above method is simply concatenating strings. Each column from the database is referenced by a method, so self.user refers to the user field of a record, and similarly self.ext refers to the ext field of a record. We then change our original call to

options_from_collection_for_select(@extensions, ‘ext’, ‘userExt’)

to match our newly defined method and there we go…

Selection_174

 

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 155 other followers

%d bloggers like this: