Checkbox Select Rails Plugin

November 5th, 2007 by pyrat

checkbox

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!

3 Responses to “Checkbox Select Rails Plugin”

  1. nilson Says:

    hi

    your plug-in for checkbox looks very cool, however, i cannot connect to the server for downloading it. could you pls tell another address or mail me a copy?

    thanks very much !

  2. pyrat Says:

    Hi Nilson,

    All looks fine to me, you can run script/plugin install http://vorlich.ath.cx/code/excited/plugins/checkbox_select to install it in your rails application.

    Maybe the server was down for a short time last night.

    Cheers.

  3. DJ Says:

    Cool Plugin but i think there is some limitaion of using it in case of three way HABTM relationship. Like say advertisement_category_product?

    Cheers

Leave a Reply