Self-referential many-many joins with :through

I thought I had this nailed but… now I’m seeing spots…

I’ve included my models below, feel free to ignore them. I’m really
just after an example that works. I couldnt find one on the wiki…
which is fair enough considering Ricks patch: that fixed them only went
through 5 days ago…


class Topic < ActiveRecord::Base

has_many :item_collection, :class_name => “Grouping”, :foreign_key
=> “item_id”
has_many :group_collection, :class_name => “Grouping”,
:foreign_key => “group_id”

has_many :groups, :through => :group_colletion
has_many :items, :through => :item_collection


class Grouping < ActiveRecord::Base

belongs_to :item,
:class_name => “Topic”,
:foreign_key => “item_id”

belongs_to :group,
:class_name => “Topic”,
:foreign_key => “group_id”

I’m assuming that the spelling difference for group_collection was only
type the email. Could you tell us what isn’t working? Rick’s change
some very useful error messages that should help you out.

Anyway, I think your has_many :through relationships might be backwards.

has_many :groups, :through => :group_collection

This is going to connect to the groupings table and specify the
since you specified that as the foreign key in the has_many
:group_collection relationship. It will then try to join back to the
table using group_id again, because you name the through relationship
“groups”. It tries to find a relationship on the join table that is the
singular or plural of the name of the through relationship, unless you
specify the :source option.

Do you really need a join model in this case? If your join model
doesn’t do
anything besides hold the keys to the topics table, then a regular HABTM
suit you better.

You may want to read through to
some background for changeset 4022.


On 29 Mar 2006 21:09:46 -0000, Henry T. <

Hey Lee,

Thanks for the reply. It was nice to soak up some backstory from the
ticket. I see you had a bit of grief with it. Just playing around with
the new features and seeing whats possible. I can see there is no need
for :through in this example, but is there a good reason to change it?
Easier to expand later if needs be. It looks like performance should be
the same… I see these kind of things are being said elsewhere so I’ll
keep an eye out.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs