Search code examples
ruby-on-railshas-many-throughbelongs-toself-reference

Returning source objects in self-referencing has_many, :through


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?


Solution

  • 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.