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

Ok。そのため、現在のアプリには、友情オブジェクトが必要なシナリオは実際にはありません。たとえば、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 に答える