Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

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> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata