Rails - Two-way "friendship" model (cont'd)

ruby, ruby-on-rails

Solution

railscasts episode on this topic

Problem

This is a continuation of this question: Original Question (SO) The answer to this question involved the following set of models: ``` class User < ActiveRecord::Base has_many :friendships has_many :friends, :through => :friendships #... end class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id' end <% for friendship in @user.friendships %> <%= friendship.status %> <%= friendship.friend.firstname %> <% end %> ``` This works fine if say, I have a user and I want to get all the "friendships" for which his or her id is the :user_id FK on the Friendship model. BUT, when I run something like ``` @user.friendships.friends ``` I would like it to return all User records for which that User is either the :user or the :friend in the friendship - so, in other words, return all friendships in which that user is involved. Hopefully the above makes sense. I'm still quite new to rails and hope there is a way to do this elegantly without making just a standard link table or providing custom SQL. Thank you! Tom

Original source

Related problems