2017-11-03 3 views
0

post_consultantconsultantConsultation 모델이 있습니다. post_consultantconsultant은 모두 Employee 모델에 대한 참조입니다. 그래서 당신은 말할 수 있습니다 : 그 쓰기 가정하고 어떻게레일 연결 : 동일한 모델의 모델이 2 회 발생

모델

Class Consultation < ActiveRecord::Base 
    has_one :employee # for consultant 
    has_one :employee # for post_consultant 
end 

마이그레이션

create_table "consultations", force: :cascade do |t| 
    t.boolean "showed_up" 
    t.boolean "signed_up" 
    t.integer "client_id" 
    t.integer "consultant_id" 
    t.integer "post_consultant_id" 
end 

?


올바른 모델 :

class Consultation < ActiveRecord::Base 
    belongs_to :consultant, class_name: "Employee", foreign_key: "consultant_id" 
    belongs_to :post_consultant, class_name: "Employee", foreign_key: "post_consultant_id" 
end 
+0

post_consultant 및 컨설턴트 모델입니까? – krishnar

+0

post_consultant 및 컨설턴트의 외래 키는 무엇입니까? – krishnar

+0

직원 만이 모델 –

답변

3
Class Consultation < ActiveRecord::Base 
    belongs_to :consultant, :class_name => "Employee", :foreign_key=> "consultant_id", dependent: :destroy 
    belongs_to :post_consultant, :class_name=>"Employee", :foreign_key=> "post_consultant_id", dependent: :destroy 
end 
+0

입니다. 그저 제가 시도 할 때 이상합니다 :'c = Consultation.new'. 'e = Employee.first'. 'ActiveModel :: MissingAttributeError : 알 수없는 속성 'consultant_id'를 쓸 수 없습니다. –

+0

테이블 상담에 consultant_id 및 post_consultant_id 열의 필드가 있는지 확인하십시오. 스키마 –

+0

나는 상담 테이블 –

0

당신은 같은 모델을 참조하여 여러 관계를 정의 할 수 있습니다.

Class Consultation < ActiveRecord::Base 
    has_one :consultant, class_name: 'Employee', foreign_key: :consultant_id 
    has_one :post_consultant, class_name: 'Employee', foreign_key: :post_consultant_id 
end 

참고 : 위의 구문을 사용하여 각각의 연결에 사용 유를 외국인 중 키 언급.

+0

위의 응답에 대한 의견을 참조하십시오. –