Posts filed under ‘HABTM’

Multiple Checkboxes with HABTM

Has and Belongs to Many with Multiple Check boxes

So if you are trying to do a multiple select of checkboxes and using habtm in your project, but when you submit the form, only one value was available in your controller. While you try to edit records in database but because of some error you get back to the pre field form and you found that the checkboxes checked by you gone ,then here’s the solution

Model:

	class Customer < ActiveRecord::Base
		has_and_belongs_to_many :intrests
	end

Controller code:

class CustomersController < ApplicationController
   def create
      if request.post?
         @customer=Customer.new(params[:customer])
         @customer.save
      end
   end

   def edit
      @customer=Customer.find_by_id(params[:id]) if params[:id]
      if @customer
         if request.post?
            if @customer.update_attributes(customer)
               flash.now[:message]="Update successfully "
            end 
         end
      else
        flash[:message]="Page requested by you does not exists"
      end
   end
end

Your View:

 <% form_for :customer,  do |f| -%>
    First Name:
      <%= f.text_field :first_name  -%>
    Last Name:
      <%= f.text_field :last_name -%>
      <% for  intr in total_intrests -%>
         <%= check_box_tag "customer[interest_ids][]", "#{intr.id}", interest(intr) -%> # interest is a helper method
         <%= "#{intr.name}" -%>
      <% end -%>
   <% end -%>

helper method

   def interest(i)
      if @customer
         @customer.interests.include?(i)
      else
        false
      end
   end

View generate a checkbox for every interest(all_interest=Interest.find(:all)). The name of the input is significant obviously. The trailing “[]” on the name means the end result will be the list of checked ids. This list will be stored on the @params[‘customer’] hash with the key ‘interest_ids’. When the controller calls @customer.update_attributes(@params[:customer]), it tries to call @customer.key= for each of the keys on @params[:customer]. What’s important to realize is that these keys don’t have to actually be attributes on the Customer model. All that’s important is that there’s a key= method on the model. Model automatically contains a “collection_ids=” method for habtm and has-many associations.

This method will load the objects identified by the ids and call the “interest=(list)” method on the model with the freshly loaded list. This method in turn, will compare the list to the current list of interests and delete/add interests as necessary. (more…)

Advertisements

June 29, 2007 at 9:36 am 12 comments


Calendar

December 2017
M T W T F S S
« Aug    
 123
45678910
11121314151617
18192021222324
25262728293031

Posts by Month

Posts by Category