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 heres 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]. Whats important to realize is that these keys dont have to actually be attributes on the Customer model. All thats important is that theres 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.

  1. says:

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

  2. says:

    hi mahesh

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

    Satish Chauhan

  3. says:

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

  4. says:

    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. says:

    If it is possible, show me your code

    i will try to solve your problem

  1. There are no trackbacks for this post yet.

Leave a Reply