2

这是我的用户模型:

class User < ActiveRecord::Base

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

end

这是我的友谊模型:

class Friendship < ActiveRecord::Base

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

  set_table_name :users_users
end

行。所以现在我的应用程序中实际上没有需要友谊对象的场景。例如,当我调用 User.find(1).friends 时,我不希望返回友谊对象数组。我实际上想要用户对象。

因此,当我调用 User.find(1).friends 时,如何让它返回 User 对象?

4

1 回答 1

2

你确定你不想要这个吗?

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

有了这个,User.find(1).friends 将返回一个用户数组,而不是友谊。

于 2011-05-05T06:32:58.290 回答