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

 

Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.