2

Here's my User model:

class User < ActiveRecord::Base

  has_many :friends, :class_name => 'Friendship', :dependent => :destroy

end

Here's my Friendship model:

class Friendship < ActiveRecord::Base

  belongs_to :user
  belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'

  set_table_name :users_users
end

Ok. So there isn't actually a scenario in my app right now where I need a friendship object. When I call User.find(1).friends, for example, I don't want an array of friendship objects to be returned. I actually want user objects.

THEREFORE, when I call User.find(1).friends, how can I make it return User objects?

keruilin
  • 16,782
  • 34
  • 108
  • 175

1 Answers1

2

Are you sure you don't want this?

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

With this in place, User.find(1).friends will return an array of Users, not Friendships.

mbreining
  • 7,739
  • 2
  • 33
  • 35
  • Doh! Nice simple solution. Thx. – keruilin May 05 '11 at 06:36
  • You may want to take a look at chapter 14 of the RailsSpace book. The friendship model is covered in great detail. Here's the source code: http://railsspace.com/book/chapter14 – mbreining May 05 '11 at 06:39