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:
http://dev.rubyonrails.org/changeset/4022 that fixed them only went
through 5 days ago…

Cheers
-henster


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

end



class Grouping < ActiveRecord::Base

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

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


I’m assuming that the spelling difference for group_collection was only
when
type the email. Could you tell us what isn’t working? Rick’s change
added
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
group_id,
since you specified that as the foreign key in the has_many
:group_collection relationship. It will then try to join back to the
topics
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
may
suit you better.

You may want to read through http://dev.rubyonrails.org/ticket/4289 to
see
some background for changeset 4022.

-Lee

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.

Cheers
-h