Programming in Paradise

Monday, January 30, 2006

Rails Recipe #1 - Adding Items in a HABTM Relationship

First recipe in what may turn out to be an ongoing thing.

If you have a HABTM relationship, say between people and their pets, and you want to assign multiple pets to a person in one shot, then your view would have something like this:

<%= form_tag :action => 'add_pet', :id => %>
<% @pets.each do |pet| -%>
<div><%= check_box_tag 'pet[]', %></div>
<% end -%>
<%= end_form_tag %>

Your controller would have something like this:

def add_pet
@person = Person.find(params[:id])
Pet.find(params[:pet]).each do |pet|
@person.pets << pet
redirect_to(:action => 'list_pets', :id =>
@pets = Pet.find(:all).delete_if { |p| @person.pets.include?(p) }

When receiving a GET request the action loads the person and a list of pets not already assigned to the person. That last line basically goes through the array returned by Pet.find(:all) and deletes the array item if the expression in the block (@person.pets.include?(p)) returns true.

When receiving a Post request the action finds all pets which match the supplied ids in the :pet array. That is accomplished by setting the check box name to pet[] which indicates that the HTTP param should be an array filled with all of the checked items from the view. Then it loops through those items and adds each one to @people.pets and finally redirects to some list of the person's pets.


Post a Comment

Links to this post:

Create a Link

<< Home