Checkbox Select Rails Plugin

November 05, 2007

I had the problem of there not being a simple form rendering solution for has_and_belongs_to_many ActiveRecord relations. I found a partial solution here: http://railshacks.blogspot.com/2007/09/helper-checkboxcollection.html

I have modified the original code slightly, and extracted it to a plugin. To install it:

  ./script/plugin install http://vorlich.ath.cx/code/excited/plugins/checkbox_select

In your model you are manipulating in the form:

  class Advertisement < ActiveRecord::Base

    include CheckboxSelectable
    has_and_belongs_to_many :categories
    validates_presence_of :name
    validates_uniqueness_of :name

  end

The include is the important bit.

In your view:

  <%= checkbox_select('advertisement', 'categories', @categories, 'name') %>

In your controller add the update_check_list method:

  def create
    @advertisement = Advertisement.new(params[:advertisement])
    @advertisement.update_check_list(params, 'Category')

    respond_to do |format|
      if @advertisement.save
        flash[:message] = 'Advertisement was successfully created.'
        format.html { redirect_to advertisements_url }
        format.xml  { head :created, :location => advertisement_url(@advertisement) }
      else
        assigns
        format.html { render :action => "new" }
        format.xml  { render :xml => @advertisement.errors.to_xml }
      end
    end
  end

I still need to write a collection of tests for this plugin. If you have the time please write them for me!