Rails - A Two-Way Friendship Model (continued)

This is a continuation of this question: Original Question (SO)

The answer to this question included 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 great if I say I have a user and I want to get all β€œfriendships” for which his or her identifier is: user_id FK on the friendship model. BUT when I run something like

 @user.friendships.friends 

I would like for him to return all user records for which this User is either a user or a friend: friendship - in other words, to return all the friendships in which this user is involved.

Hope this makes sense. I am still new to rails and hope there is a way to do this elegantly without doing just a standard reference table or providing custom SQL.

Thanks!

Tom

+6
ruby ruby-on-rails
source share
4 answers

railscasts episode on this subject

+7
source share

You can't just use @ user.friendships here because it will only give you friendships where @ friendship.user_id == @ user.id. The only thing I can think now is to just do

 Friendship.find_by_user_id(@user.id).concat Friendship.find_by_friend_id(@user.id) 
+3
source share

my solution is the scope:

 # model class Message < ActiveRecord::Base belongs_to :sender, :class_name => "User" belongs_to :recipient, :class_name => "User" scope :of_user, lambda { |user_id| where("sender_id = ? or recipient_id = ?", user_id, user_id) } end # in controller @messages = Message.of_user(current_user) 
+2
source share

From the railscast link:

 # models/user.rb has_many :friendships has_many :friends, :through => :friendships has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" has_many :inverse_friends, :through => :inverse_friendships, :source => :user 
+1
source share

All Articles