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
Post a Comment
eSpace podcast Prodcast
Archive
- September 2011
- April 2011
- March 2011
- December 2010
- November 2010
- September 2010
- August 2010
- July 2010
- June 2010
- April 2010
- March 2010
- November 2009
- October 2009
- September 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- November 2008
- October 2008
- September 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- January 2008
- April 2007
- March 2007
Latest Comments
- SpectraMind Commented on Egypt Wins UK's National Outsourcing Association Award
- Rofaida Awad Commented on Go Egypt Go!
- Different Mike Commented on Only idiots change their iPhone root password!
- Mike Commented on Only idiots change their iPhone root password!
- smile Commented on Only idiots change their iPhone root password!

