Not binding your selection list to a particular model in Rails


In Rails, we use collection_select helper to display values from a particular model using a drop down but it is generally tied to a particular model, i.e. if we look at the generated html then we see something like

select name="customer[customer_search]" id="customer_customer_search"

What if we want something like:

select name="customer_search" id="customer_search"

Then we can simply use select_tag helper and get the values from our model like this

customers = Customer.find(:all, :order => 'first_name').map{|x| [x.full_name] + [x.id]}
select_tag(:customer_search, options_for_select(customers))

If we don’t want to display the values from model and would like to feed in something simple and manually, then

customers = [['text_to_display1', 'value1'], ['text_to_display2', 'value2']]
select_tag(:customer_search, options_for_select(customers))

If text_to_display and its value both are same then we can use something as simple as:

customers = ['wee', 'asdf']
select_tag(:customer_search, options_for_select(customers))

Advertisements

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