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.

9 Comments »

  1. mahesh said

    thank u but some what unable to understand clearly,please give me in some datailed one

  2. hi mahesh

    Let me know what point you are not getting ?
    and what more detail you want ?

    Satish Chauhan

  3. mahesh said

    how to display the content of FCK Editor without displaying HTMLtags at users display in ruby on rails

  4. mahesh said

    thank u for reply,
    i am creating a list of items with every item containing checkboxes.as i have to select some items by clicking checkbox. and when i click on the delete button i have to delete the selected items from the list,and i have to display the same page with remaining list of items.
    for that i have declare an array for checkboxes and how i can pass the array to controller to delete the items..
    can u please give me the explanation for this …..

  5. If it is possible, show me your code

    i will try to solve your problem

  6. Travis said

    Thanks for the code posting. This is exactly what I was looking for!

  7. hiutopor said

    Hi

    Very interesting information! Thanks!

    G’night

  8. neil said

    hi there, i’m a having some difficulties to add records in my database.
    i tried many ways but cannot succeed.
    please help me to give some ideas what’s wrong with my code
    by the way, i want to develop a webpage to list all students’ name and tick the checkboxes then click save to save all the students’ attendance.

    def createattendance
    if params[:id]
    @attendance = Teachersubject.find(params[:id])
    else
    @attendance = Attendance.new
    end
    if request.post?
    @attendance.attributes = params[:attendance][:student_ids]
    begin
    @attendance.transaction(@attendance) do
    @attendance.save!
    @attendance.reload unless @attendance.id
    raise ActiveRecord::RecordInvalid unless @attendance.valid?
    redirect_to :action=>’eattendance’
    end
    rescue ActiveRecord::RecordInvalid
    end
    end
    end

    function checkedAll (id, checked) { var el = document.getElementById(id);
    for (var i = 0; i < el.elements.length; i++) {
    el.elements[i].checked = checked;
    }
    }

    ‘createattendance’%>

    Select Subject

    <option value=”">

    [:day, :month, :year], :start_year => 2007, :end_year => Time.now.year)%>

    <input id=”attendance[class1_id]” name=”attendance[class1_id]” size=”1″ type=”varchar” value=”"/>

    []

    <INPUT type=”hidden” name=’student[ids][]‘ value=”">

  9. Chris said

    Brilliant. And finally got me to use a helper method.

RSS feed for comments on this post · TrackBack URI

Leave a Comment