开发者

Returning source objects in self-referencing has_many, :through

开发者 https://www.devze.com 2023-03-02 18:52 出处:网络
Here\'s my User model: class User < ActiveRecord::Base has_many :friends, :class_name => \'Friendship\', :dependent => :destroy

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 w开发者_如何转开发ant user objects.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消