Calamity Lane

Curious Code for Curious Coders

Select Tag Funkiness With Merb

In my ongoing travails with Merb & Friends, I’ve run across a few behaviors with the select() form helper method. Since there’s currently a dearth of examples, I thought I’d document them for myself and future googlers.

If you’re having problems getting select() to work in Merb, bear the following in mind:

If you type the following:

1
select :widget_id, :collection => Widget.all

You may get the error:

>> undefined method 'first' in <Widget:0x7fae15562fc8>

(you may also get “undefined method ‘last’”)

select() expects two options to be passed in: :value_method and :text_method. If you provide neither, Merb will assume that your collection is an array, and will default them to the ‘first’ and ‘last’ methods respectively. Add your field names or methods explicitly to make select() happy:

1
2
select :widget_id, :collection => Widget.all,
       :value_method => :id, :text_method => :name

Additionally, there’s a strange behavior, in which the :selected option appears to be ignored– when you pull your form back up after a save, the select box will be back on the default value:

1
2
select :widget_id, :collection => Widget.all,:value_method => :id,
       :text_method => :name, :selected => @whongo.widget_id

The problem here is that Merb expects the :selected option to be a string. Cast your selected value to a string and all will be well:

1
2
select :widget_id, :collection => Widget.all,:value_method => :id,
       :text_method => :name, :selected => @whongo.widget_id.to_s