Rails: has_many documentation mistake

2

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 this:

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'

Written By:

Haitham Mohammad (e-haitham.blogspot.com)

Comments

1

google also have some problems with Rails :http://i41.tinypic.com/24dna5x.png :) !

2

Thanks so much. Very helpful!

Post a Comment

eSpace podcast Prodcast

RSS iTunes