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?