2

가 여기 내 사용자 모델의를 통해 :돌아 소스는 자체 참조 has_many에서 객체 :

class Friendship < ActiveRecord::Base 

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

    set_table_name :users_users 
end 

확인 :

class User < ActiveRecord::Base 

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

end 

가 여기 내 우정 모델입니다. 그래서 실제로 내 우연 객체가 필요한 시나리오가 실제로 없습니다. 예를 들어, User.find (1) .friends를 호출하면 반환 할 우정 개체 배열을 원하지 않습니다. 실제로 사용자 개체가 필요합니다.

그래서 User.find (1) .friends를 호출하면 어떻게 User 객체를 반환 할 수 있습니까?

답변

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는 Friendship이 아닌 Users 배열을 반환합니다.

+0

Doh! 좋은 간단한 솔루션. 고마워. – keruilin

+0

RailsSpace 서적의 14 장을 참조하십시오. 우정 모델은 아주 자세하게 다룹니다. 다음은 소스 코드입니다. http://railsspace.com/book/chapter14 – mbreining