Selecting First Radio Button List Item in Rails

Those of you who’ve done this a thousand times can move along. This is not the post you are looking for. But for those wanting to know why the first option in a Radio Button List isn’t being selected, this post could be a sweet little reference.

Here’s our Radio Button List. We want the first item selected. We don’t care what it is, we just want it selected.

No lead-up on this post. This is how you do it.

Now we can talk a little. You might have been doing something very similar, perhaps the equivalent of

<%= radio_button_tag “store_ids[]”,, :checked => (store == @stores.first) %>

You would think that works, but instead it sets “checked” to true for all radio buttons and selects the final radio button list item.

If you read the description of the radio_button_tag at APIDock you’ll see

radio_button_tag(name, value, checked = false, options = {})

The trick is to set the radio button as “false” and then pass our @stores.first test as an OPTION.

Bonus! Processing a Radio Button List in the Controller

As a bonus (and because this post only has two screenshots) here is how you might want to process the item selected from a Radio Button List in your controller.

The secret sauce is


Because we made certain that at least one Radio Button item is selected on page load we have the confidence that the :store_ids[] array we’re passing has a single item, or :store_ids[0] which we then can convert to an integer.