1

I have a Friends model with user_id and friend_id...both are id's back to specific users.

What I'd like to able to do is something like this:

@relationship = Friend.find_by_user_id(current_user.id)
@relationship.friend.username

Where I can basically pull the user through the friend_id column in the same way I can do @relationship.user.username.

How would I setup my associations to pull that off?

Shpigford
  • 24,748
  • 58
  • 163
  • 252

2 Answers2

0

Isn't this just a many-to-many situation.

I think there is a perfect solution in Many-to-many relationship with the same model in rails?

Hope this help!

Community
  • 1
  • 1
0

Use class_name if your column doesn't reflect the convention expected:

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: 'User'
end

Note that I modified the model name to Friendship to better reflect the use of this model. Also, you can make it easier for yourself if you revise your User model to look like this:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships

  has_many :friendships_of, :class_name => 'Friendship', :foreign_key => :friend_id
  has_many :friends_of, :through => :friendships_of, :source => :user
end

Now to see all the user's friends:

current_user.friends.map(&:username)

And to see who has 'friended' the user:

current_user.friends_of.map(&:username)
PinnyM
  • 35,165
  • 3
  • 73
  • 81