views:

318

answers:

2

I recently became drunk on the Rails koolaid and am trying to create the following:

User model (this is fine)

id

Link model (associated with two Users)

id
user_id1
user_id2

Is this an instance in which I would want to use the has_and_belongs_to_many association type on the Link model? How should I do this?

Ultimately, I would like to be able to have a user object and call @user.links to get all links involving that user...

I'm just not sure what the best way to do this in Rails is.

Thanks!

Tom

+10  A: 

You will very likely want two models structured as follows:

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 

# ...and hence something like this in your view
<% for friendship in @user.friendships %>
  <%= friendship.status %>
  <%= friendship.friend.firstname %>
<% end %>

(This pattern is from a post made by Ryan Bates about two years ago during this discussion on RailsForum.)

Joe
Awesome, thanks!
cakeforcerberus
+1  A: 

You can create A Join Model that relation between the Link between the two users models

so basically


class User

  has_many :links, :through => :relationships

end

class Relationship

  belongs_to :user_id_1, :class=> "User"
  belongs_to :user_id_2, :class=> "User"

end

Rishav Rastogi