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:

Controller Code:

Your View:

Helper method

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.

5 Comments

  • on 12 Jul 2007 at 7:52 pm #

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

  • on 13 Jul 2007 at 11:08 am #

    hi mahesh

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

    Satish Chauhan

  • on 13 Jul 2007 at 7:17 pm #

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

  • on 16 Jul 2007 at 7:14 pm #

    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 …..

  • on 17 Jul 2007 at 8:30 pm #

    If it is possible, show me your code

    i will try to solve your problem

  • Leave a Reply