In this fourteenth part of a multi-part series on the Action Pack library, you'll learn how to add categories to the Events form and handle categories in the Events controller. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
In Chapter 5, we added categories to the Event model, but neither our controller nor our templates know about this yet. Let’s remedy that now, starting with the events form. Add the code shown in bold in Listing 6-18 to the form partial in app/views/events/_form.rhtml .
The select_tag method is another of Action View’s form helpers. It creates a drop-down selection box, or if the :multiple option is set to true (as it is in our case), a multiple-choice selection box. By including a set of square brackets with the tag’s name ( categories ), we’re telling Rails to generate a collection of values in the params that are submitted.
It’s important to note that select_tag generates only the HTML select tag. We need to generate the actual option tags ourselves. Again, Rails provides a helper to take care of the heavy lifting: options_for_select . The options_for_select helper accepts a collection and returns a string of option tags. Given a collection where the elements respond to first and last (such as a two-element array), the firsts serves as the option test, and the lasts serves as the option values. A second argument can be passed to options_for_select to specify any options that should be preselected. In our case, we’re passing in all the category_ids for the given event so they will be preselected. This is easily the most advanced helper we’ve looked at so far, so it’s okay to take it on faith a bit. Once we add the appropriate code to handle categories in the controller, everything should “just work.”
You can find the full documentation for select_tag and options_for_select helpers in the Ruby API: