Tagged with form

Ruby on Rails – Disabling a select tag using the select helper

There is a bit of a subtlety to this, and it took me a while to figure this out. If I used the select_tag helper I was able to disable the select menu, but using comparable code with the select helper it wouldn’t be disabled.

<% options= ['one', 'two', 'three', 'four'] %>

<%= select_tag :content, options_for_select(options), :disabled => true %>
<%= f.select :content, options, :disabled => true %>

Here my select_tag would be disabled like I wanted, but the f.select would not be. This made me quite perplexed, and with more research I discovered it’s because the “disabled” option for the select helper has been mapped to allow the developer to disable specific elements. For example, this code similarly yields differing behavior:

<% options= ['one', 'two', 'three', 'four'] %>
<% disabled_options= ['two', 'four'] %>

<%= select_tag :content, options_for_select(options), :disabled => disabled_options %>
<%= f.select :content, options, :disabled => disabled_options %>

In the case of the select_tag helper, the menu is still disabled as the disabled_options array will evaluate to true. For the select helper, however, the disabled_options array will tell the helper to set the options that match elements of the array to disabled. This is where I remained stuck for a while, not being able to figure out a way to use the select helper to disable the menu. Then looking more closely at the API documentation, I noticed a difference between the two helpers.

select_tag(name, option_tags = nil, options = {})

select(object, method, choices, options = {}, html_options = {})

The select helper has an additional set of parameters called “html_options” after the options. The select_tag helper conversely simply uses any parameters in its options array that don’t match expected options as html attributes. Based on this I wondered if I passed a hash array for the options parameter, if I could explicitly pass disabled as an html option, as follows:

<% options= ['one', 'two', 'three', 'four'] %>

<%= select_tag :content, options_for_select(options), :disabled =>true %>
<%= f.select :content, options, {}, :disabled => true %>

Sure enough this worked, and gave me the same behavior for both helpers! I was quite surprised to find such inconsistent behavior for these two helpers. It was reminiscent of my experiences with PHP and I’m disappointed to see it here in the Rails API. I would be curious to hear an explanation for why these two helpers are so different.

Happy Coding!

Tagged , , , , , , , , ,