I know this question has been asked before on Stack Overflow, but the answers aren't doing it for me in ways I can explain. My general approach was inspired by this tutorial.
What I'm trying to do, is create a really simple model for friending users that creates an equivalent friendship on both ends with a single record.
At the db level, I just have a 'friendships' table that just has a user_id, a friend_id, and an is_pending boolean column.
In user.rb I've defined the relationship as:
has_many :friendships
has_many :friends, through: :friendships
In friendship.rb, I've defined the relationship as:
belongs_to :user
belongs_to :friend, :class_name => 'User'
If I add a friendship, I can access as follows:
> a = User.first
> b = User.last
> Friendship.new(a.id, b.id)
> a.friends
=> #<User b>
That's perfect, but what I want is to also be able to go in the other direction like so:
> b.friends
Unfortunately, with the relationship defined as it is, I get an empty collection. The SQL that runs shows that it's searching for user_id = b.id. How do I specify that it should also search for friend_id = b.id?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…