Creating Selection Lists
Selections lists are, in many ways, like radio buttons on a larger scale. Rather than filling a screen with radio buttons, a list lets you hide the options except during that critical time when you’re actually making a selection. Showing radio buttons for over 190 countries would take up a huge amount of screen real estate. Selection lists offer a much more compact but still convenient way for users to make choices.
Rails has a number of helper methods for creating selection lists,
but the simplest place to start is the select
method. In its most basic form, select
takes two arguments: the attribute that
populates it and a set of choices. Choices can be represented in a
number of different ways, from a simple array of strings to a hash or
other more complex set of values.
Note
At the time this was written, this simplest form of select
wasn’t actually documented in the
Rails API docs. If you look at the documentation for a function and it
seems like it’s more complex than you need, it’s sometimes worth
experimenting to see whether a simpler form will work. The docs often
seem to give priority to more complex use cases. (As you become a
guru, you’ll likely be able to look at the Rails source code and
figure it out, but Ruby’s many options make it tricky at
first.)
Using an array of strings, the call to create a selection list might look like:
<p> <b>Country</b><br /> <%= f.select (:country, ['Canada', 'Mexico', 'United Kingdom', 'United States of America'])%> </p> ...
Get Learning Rails now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.