Having set up my self referential user -> friend relationship with the following code all seems to be working well except for one thing. Adding and deleting friends. Here is the code for the models: class Friendship < ActiveRecord::Base belongs_to :friendshipped, :foreign_key => "user_id", :class_name => "User" belongs_to :befriendshipped, :foreign_key => "friend_id", :class_name => "User" end class User < ActiveRecord::Base has_many :friendships, :foreign_key => 'user_id', :class_name => 'Friendship' has_many :befriendships, :foreign_key => 'friend_id', :class_name => 'Friendship' has_many :friends, :through => :friendships, :source => :befriendshipped has_many :befrienders, :through => :befriendships, :source => :friendshipped end When i execute the following code strange things happen: user = User.find 1 friend = User.find 2 user.friends << friend This piece of code appears to work but upon inspection of the generated sql a friendship record is created with user_id = 2 where it should be 1 and the friend_id is set to NULL where it should be 2. It seems that the ability to add friends to a user this way using self-referential relationships is broken. Also deleting does not working either if i go user.friends.delete(friend) an update statement is generated, very confusing. I am not sure whats going on here at all. This functionality works for normal has_many :through relationships just not my self referential ones. Any ideas?
on 2007-03-22 01:21
on 2007-03-22 23:10
For anyone that may stumble upon this i have found a workaround although i still believe it is a bug in rails. When your self referential join is setup like above to add friends to a user instead of using this : user = User.find 1 friend = User.find 2 user.friends << friend Use this: user = User.find 1 friend = User.find 2 user.friendships.create(:user_id => user.id, :friend_id => friend.id) For deleting instead of using this: user.friends.delete(friend) Use this: user.friendships.destroy(user.friendships.find_by_friend_id(friend)) Hopefully this helps someone, any input from someone more experienced than me is more than welcome, as i claim to be no expert.
on 2007-03-24 03:26
I ave noticed this behaviour also. Can anyone confirm if this is a bug or not ?? How does one confirm this.
on 2007-03-24 05:42
I have created a plugin called Simply Rich Association that simplifies the self referential many to many relationship implementation. Check out the Rubyforge for details: http://sra.rubyforge.org I am still working on setting up the Subversion repository. For now, you can unzip the file http://www.zepho.com/download/simply_rich_association.zip into your vendor plugin directory.
on 2007-03-27 04:09
@Bala Paranj This is find for habtm but what about has_many :through for join tables that need extra columns.