Has Many Through Discoveries

written by Cyx on June 13th, 2006 @ 01:45 PM

A guy at ruby forum posted some code regarding self referential has_many :through associations.

(refer to this post http://www.ruby-forum.com/topic/67335#new)

Tracing the code led to the culprit at reflections.rb

in line 163 of reflections.rb

source_reflection_names.collect do |name| through_reflection.klass.reflect_on_association(name) end.compact.first

For his domain model, this would look like

[:potential_friend, :potiential_friends].collect do |name| Relationship.reflect_on_association(name) end.compact.first

where reflection_on_association would check for all the associations declared for the Relationship class. Since there was no declaration of :potential_friend or :potential_friends this returns nil, and hence is the reason for the exception.

So what does this mean ultimately?

Whenever you declare something like

class Membership end class User has_many :memberships has_many :groups, :through => :memberships end

be sure that you declare a belongs_to :group in your Membership. Unlike other assocation types in Rails, has_many :through makes it mandatory that you declare both sides of the relationships.