has_and_belongs_to_many Problem

Hi all

I'm having a problem with has_and_belongs_to_many (habtm)...

Here is my setup:

tables: customers, customergroups and a join-table called
customers_customergroups

customers has an id as pk and so does customergroups. the join table
has customer_id and customergroup_id (as well as an id)

both models include the habtm statement, one with :customergroups and
the other with :customers

No I do the following:

customer = Customers.find(123)

at this point i would like to say: customer.customergroups.to_xml.

The error message I get here is: uninitialized constant
Customers::Customergroup

What am I doing wrong? Can anyone help?

Try changing the name of the join table to customergrous_customers.
Also with a straight habtm the join table doesn't need an ID column,
though I don't know off hand if it breaks anything to have one.

I already switched both parts to customergroups_customer, no effect. I
now did remove the id column, because I don't really need it, but
still no luck.

The join table should be called customergroups_customers (notice the s
on the end of customers) and should have 2 columns customer_id and
customergroup_id their should be no primary key or any other column.

in your customer.rb file you should have as the second line
  has_and_belongs_to_many :customergroups

and in your customergroup.rb file you should have
  has_and_belongs_to_many :customers

(notice the models have singular names and the associations have
pluralised names)

Actually I'm pretty sure that the default table name would be
customers_customergroups It get's generated by the sort order of the
(singular) class names and "customer" < "customergroup"

Of course it can be explicitly set using the :join_table option on the
:has_and_belongs_to_many relationship.

Personally I've ditched habtm and the general drift in Rails
development is to avoid it. If you use an explicit join table it's a
little easier to manage (IMO) and you gain the benefit of easily
handling attributes on the association. Just to reduce the long names
I'd use something like this:

Customer (as is)
CustomerGroup (as is)
GroupMembership (customer_id, customer_group_id)

Customer
has_many :group_memberships
has_many :customer_groups, :through :group_memberships

GroupMembership
belongs_to :customer
belongs_to :customer_group

CustomerGroup
has_many :group_memberships
has_many :customers, :through :group_memberships