Collection Form Helpers [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

You are probably familiar with the form helper collection_select. It's a form helper that returns a <select> element and <option> tags for a collection. For example:

  collection_select(:post, :author, Author.all, :id, :name)
  # Returns: 
  # <select name="post[author_id]"> 
  #   <option value="1">Kevin</option> 
  #   <option value="2">Rida</option> 
  #   .. 
  # </select>

This method is very convenient for a belongs_to association, especially when you have lots of options for the user to select from.

In Rails 4, two similar form helpers have been added:

Example

Given that you have two models Post and Category where post has many categories:

  class Post < ActiveRecord::Base
    has_many :categories
  end

You can allow the user to select multiple categories by setting category_ids using collection_check_boxes:

  collection_check_boxes(:post, :category_ids, Category.all, :id, :name)
  # Returns:  
  #   <input id="post_category_ids_1" name="post[category_ids][]" type="checkbox" value="1" checked="checked" />
  #   <label for="post_category_ids_1">Ruby</label>
  #   <input id="post_category_ids_2" name="post[category_ids][]" type="checkbox" value="2" />
  #   <label for="post_category_ids_2">Javascript</label>
  #   ...
  #   <input name="post[category_ids][]" type="hidden" value="" />
  #

The collection_radio_button method accepts the same parameters, but it returns radio buttons instead:

  collection_radio_buttons(:post, :category_ids, Category.all, :id, :name)
  # Returns:  
  #   <input id="post_category_ids_1" name="post[category_ids][]" type="radio" value="1" checked="checked" />
  #   <label for="post_category_ids_1">Ruby</label>
  #   <input id="post_category_ids_2" name="post[category_ids][]" type="radio" value="2" />
  #   <label for="post_category_ids_2">Javascript</label>
  #   ...
  #

Yet another convenient helper from Rails to make developers happy!

Rida

This post is by Rida Al Barazi. Rida is a passionate web developer experienced in building web applications for startups. He started working with Rails in 2005, co-authored Beginning Rails 3, and has spoken at conferences around the world.


Comments

comments powered by Disqus