2017-01-01 2 views
0

모두에게 새해 복 많이 받으세요!레일 5 : "belongs_to through"제휴 종류

나는 고전 has_many through association 있습니다

class Physician < ApplicationRecord 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Appointment < ApplicationRecord 
    belongs_to :physician 
    belongs_to :patient 
end 

class Patient < ApplicationRecord 
    has_many :appointments 
    has_many :physicians, through: :appointments 
end 

그러나 지금은 다른 모델과 belongs_to 관련되는 일부 class Exampleclass Appointment에서 has_many 연결을 추가 할 필요 class Examplebelongs_to 관련 될 것이다.

가능한 경우 이러한 종류의 분류를 설정하는 방법은 무엇입니까? 고맙습니다.

이 질문을 downvoted 왜 업데이트

이해하지 않습니다. 여기 내가 class Example에 필요한 것입니다 : 2

확인

class Example < ApplicationRecord 
    belongs_to :appointment 
    belongs_to :model_bbb 
end 

업데이트, 나는 this answer에서 솔루션을 사용할 수 있습니다 알아 냈어. 기본적으로 나는 "약속"모델을 삭제하고이 같은 class Example을 가질 수

class Example < ApplicationRecord 
    belongs_to :physician 
    belongs_to :patient 
    belongs_to :model_bbb 
end 

그리고 의사 및 환자에 내가 has_many :examples 다른 through 관계를 할 수 있습니다. 나는 class Appointment의 상대적으로 작은 테이블을 가질 수 있었기 때문에 다소 이상한 belongs_to through 것을하고 싶었지만, class Example 테이블이 꽤 큰 것으로 예상됩니다. 그래서 제 처음 생각은 여러 번 복제 될 여분의 칼럼을 만드는 것이 아니 었습니다.

+0

질문을 이해할 수 없습니다. 마지막 스 니펫에 어떤 문제가 있습니까? 그건 그렇고, 분류를 개선하기 위해 태그를 편집하십시오 - 이것은 ruby-on-rails-5 스레드이기 때문에. – marmeladze

답변

0

그냥 has_many 또는 has_many through를 Appointment 모델 클래스에 추가 할 수 있습니다.

belongs_to 연관은 외래 키가있는 테이블에서 항상입니다. 따라서 모델링에 익숙하다면 examples 테이블에 예를 들어 appointment_id가 있어야합니다.

다른 테이블과의 관계에서 연관 테이블을 사용하는 데 문제가 없습니다. 실제로 중간 테이블을 사용한다는 것은 다른 정보를 저장할 수 있다는 것입니다 (다른 HABTM을 수행하는 것입니다).

+0

고맙습니다. 위의 업데이트 2를 확인하십시오. 그 순간 가장 효과적인 해결책 인 것 같습니다. 다른 아이디어가 있으면 의견을 말하십시오. – matiss