Wednesday, December 3, 2008

Rails: has_many documentation fault

I was going through an implementation case when I wanted to add a has_many :through relation from a 'User' model to itself, through a 'Friendship' model. According to the documentation of has_many:
:through Specifies a Join Model through which to perform the query. Options for :class_name and :foreign_key are ignored, as the association uses the source reflection.
The relation should infer the class name and the foreign key from the source option. i.e. If the source is :post, then the class is Post and the foreign key is post_id.

The problem was that I had a special case, where a self many-to-many relation is needed. There was a User-to-User join model called Friendship. Its table has two relevant columns: user_id and friend_id. The association using :source would look like that:
has_many :friends, :through => :friendships, :source => :user

This wouldn't be right because the relation will use 'user_id' to do the join instead of 'friend_id'.

To my surprise, the documentation was not right in this case. Adding the :class_name and :foreign_key options instead of :source worked like a charm.

has_many :friends, :through => :friendships, :foreign_key => 'friend_id', :class_name => 'user'

No comments: