사용자 (모델) 계층 구조, 자기 참조 조인
-
06-07-2019 - |
문제
나는 두 레벨의 사용자 관계를 갖는 방법을 알아 내려고 노력하고 있습니다.
사진 작가는 고객이 있습니다. 고객에게는 사진 작가가 하나 있습니다. 둘 다 사용자입니다.
다음과 같은 것처럼 보이는 사용자 모델이 있습니다.
class User < ActiveRecord::Base
#authlogic
has_many :client_associations,
:foreign_key => 'client_id',
:class_name => 'Association',
:dependent => :destroy
has_many :clients, :through => :client_associations
has_one :photographer_association,
:foreign_key => 'photographer_id',
:class_name => 'Association',
:dependent => :destroy
has_one :photographer, :through => :photographer_association
end
그리고 다음과 같은 것처럼 보이는 연관성 모델
create_table "associations", :id => false, :force => true do |t|
t.integer "photographer_id"
t.integer "client_id"
end
class Association < ActiveRecord::Base
belongs_to :client, :class_name => 'User'
belongs_to :photographer, :class_name => 'User'
end
일부 데이터로 채우고 콘솔을 발사하면 user.clients.all 또는 user.photographer를 실행하면 빈 배열이 제공됩니다.
내가 뭘 잘못하고 있죠?
해결책
외국 _keys를 전환해야합니다.
has_many :client_associations,
:foreign_key => 'photographer_id',
:class_name => 'Association',
:dependent => :destroy
has_many :clients, :through => :client_associations
has_one :photographer_association,
:foreign_key => 'client_id',
:class_name => 'Association',
:dependent => :destroy
has_one :photographer, :through => :photographer_association
제휴하지 않습니다 StackOverflow