Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 301
cakeforcerberus Avatar asked Jul 01 '09 19:07

cakeforcerberus


2 Answers

railscasts episode on this topic

like image 131
damianlegawiec Avatar answered Oct 02 '22 21:10

damianlegawiec


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

Friendship.find_by_user_id(@user.id).concat Friendship.find_by_friend_id(@user.id)
like image 28
alex.zherdev Avatar answered Oct 02 '22 22:10

alex.zherdev