Unique Marketing, Guaranteed Results.

Has and Belongs To Many (HABTM) Checkboxes With Rails

April 1st, 2009 by Aaron Murphy

I was trying to setup an HABTM list with a checkbox, similar to Ryan Bates’ railscast. The problem was the empty http posts when all checkboxes are cleared.

The code that I was emulating is:

# products_controller.rb
def update
  params[:product][:category_ids] ||= []
  #...
end

The problem I was having is that

params[:product]

was nil as the http post sent nothing because I only had checkboxes on my form. Defaulting to

[]

wasn’t valid for the

update_attributes

method.

The hack that I finally came up with was like this:

# products_controller.rb
def update
  if params[:product].nil?
    @products.categories = []
  else
    @products.update_attributes(params[:product])
  end
  redirect_to :action => :index
end

So it turns out, in this HABTM scenario, one can address the entire list of categories with an array.

  • Facebook
  • Google Bookmarks
  • email
  • NewsVine
  • Slashdot
  • Technorati
  • Yahoo! Buzz
  • BlinkList
  • Print
  • Propeller
Filed under: Programming — Tags: , , , — Aaron Murphy @ 2:50 pm on April 1, 2009

1 Comment

  1. Or just include a hidden field in the form:

    hidden_field_tag(“product[category_ids][]“, “”, :id => nil)

    Put this before the first checkbox.

    Comment by Scott Johnson — October 23, 2009 @ 2:12 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment


Copyright © 2005-2011 PMA Media Group. All Rights Reserved