0

HABTM의 기본 문제가 있습니다. 나는 단순히이 중 첫 번째 가수 (별개의) 앨범의 수를 찾는 방법을 알고 싶은 세 가지 모델, 가수, 노래, 앨범HABTM이 포함 된 세 가지 모델 첫 번째 쿼리에서 세 번째 모델에 도달하는 방법

Singer <=habtm=> Song <=habtm=> Album 

있습니다. 이 단일 문제는 어떻게 처리합니까? 쿼리를 하나의 라이너로 줄일 수 있습니까? 제안 할 수있는 더 나은 데이터 모델이 있다면 그것은 또한 환영합니다.

답변

1

Use :through

has_many : 협회 종종 다른 모델 대다 연결을 설정하기 위해 사용된다 통하여. 이 연결은 모델을 선언 할 때 세 번째 모델을 진행하여 모델의 인스턴스가 0 개 이상 일치 할 수 있음을 나타냅니다. 예를 들어 환자가 의사를 만날 약속을하는 의료 행위를 생각해보십시오. 관련 협회의 선언은 다음과 같이 수 :

class Physician < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Appointment < ActiveRecord::Base 
    belongs_to :physician 
    belongs_to :patient 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end 

UPDATE 1 :

일부가 테이블을 조인하십시오.

class Physician < ActiveRecord::Base 
    has_many :appointment_physicians 
    has_many :appointments, through :appointment_physicians 
end 

class Appointment < ActiveRecord::Base 
    has_many :physicians, through :appointment_physicians 
end 

class AppointmentPhysician < ActiveRecord::Base 
    belongs_to :appointment 
    belongs_to :physician 
end 
+0

여기 약속은 한 명의 의사에게 속하지만 약속이 많은 의사에게 속할 수있는 요건이 있으며 의사는 많은 약속을 가질 수 있습니다. 의사 '<=> 약속'<=> 환자 '는 요구 사항입니다. –

+0

조인 테이블을 사용하십시오. 설정을 보여주기 위해 답변이 업데이트되었습니다. –

+0

이렇게하면 2 개의 테이블에 대한 문제를 해결할 수 있습니다. 환자는 분실했습니다 –

관련 문제