has_and_belongs_to_many with checkboxes

Hello all,

I’m trying to get my head round HABTM, and need to build a checkbox list. I have the following models

class Supplier < User

has_one :supplier_profile, :dependent => :destroy

has_one :profile, :foreign_key => ‘user_id’, :dependent => :destroy

end

class SupplierProfile < ActiveRecord::Base

belongs_to :supplier

has_and_belongs_to_many :supplier_categories

end

class SupplierCategory < ActiveRecord::Base

has_and_belongs_to_many :supplier_profiles

end

and I have my link table: supplier_categories_supplier_profiles

I have a controller, suppliers_controller, a snippet of which looks like

def new

@supplier = Supplier.new

@supplier_profile = @supplier.supplier_profile = SupplierProfile.new

@supplier_categories = SupplierCategory.find(:all)

end

def create

@supplier = Supplier.new(params[:supplier])

@supplier_profile = @supplier.supplier_profile = SupplierProfile.new(params[:supplier_profile])

if @supplier.save

flash[:notice] = ‘Link was successfully created.’

redirect_to :action => ‘list’

render :text => “saved”

else

render :action => ‘new’

render :text => “not saved”

end

end

and the checkbox area of my form looks like

Category

<% for category in @supplier_categories %>

<%= check_box_tag('supplier_profile[supplier_category_ids][]', category.id) %>

<%= category.name %>

<% end %>

Basically it’s not saving and I’m not entirely sure why not. If I remove the supplier from the new and create methods then it will save the supplier_profile with any checked checkboxes but something isn’t quite right with the supplier.

Any ideas?

Alastair

I was having a problem running a test using a fixture called receives. The error was class “Receife” not found. Being new at this it took me a while to figure out that I needed an inflection rule, because receives was being inflected to receife and then classify camelcased it into Receife.

“receives”.singularize => “receife” “receives”.classify => “Receife” I suspect the two rules responsible for this are:

C:\ruby\lib\ruby\gems\1.8\gems\activesupport-1.3.1\lib\active_support\inflections.rb

inflect.plural(/(?:([^f])fe|([lr])f)$/i,

‘\1\2ves’)

inflect.singular(/([^f])ves$/i,

‘\1fe’) In my environment.rb, I tried creating a simple plural and singular rule, but they didn’t make any difference. I ended up creating an irregular rule, which worked fine. (Probably a DRYer solution anyway) but I’m not sure why the rules didn’t work. Inflector.inflections do

inflect>

inflect.plural

‘/^(receive)$/i’, ‘\1s’

inflect.singular

‘/^(receive)s/i’, ‘\1’ inflect.irregular ‘receive’, ‘receives’ end

Anyway, I hope this helps you avoid some unnecessary head scratching!

Regards,

Dave Dumaresq