5

을 통해, 그들은 다 대다 관계를 사용 has_many을 보여줍니다 통해과 같이 :: 레일 협회 가이드에서 관련

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 

어떻게 만들고 약속을 제거 할 것인가?

@physician이있는 경우 약속을 만들기 위해 다음과 같이 작성합니까?

@patient = @physician.patients.new params[:patient] 
@physician.patients << @patient 
@patient.save # Is this line needed? 

삭제 또는 삭제하는 코드는 어떻게됩니까? 또한, 환자가 약속 테이블에 더 이상 존재하지 않으면 파괴됩니까? 약속을 생성하는 코드에서

답변

7

는 두 번째 줄 필요하고, #build 방법 대신 #new 사용하지 않는 : 당신은 단순히 그것을 발견하고 파괴 할 수있는 약속의 기록을 파괴

@patient = @physician.patients.build params[:patient] 
@patient.save # yes, it worked 

을 :

has_many에 종속 설정 :

당신이 환자를 파괴와 함께 약속 기록을 파괴하려는 경우
@appo = @physician.appointments.find(1) 
@appo.destroy 

, 당신은 추가해야합니다

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :physicians, :through => :appointments, :dependency => :destroy 
end 
+1

감사합니다. 약속을 삭제해도 의사가 환자에게서 삭제되고 반대의 경우도 마찬가지입니다. – dteoh

+1

아니요,': dependency => : destroy'를'belongs_to'에 추가하지 않으면 않습니다. – Kevin

+0

실제로': dependency' 설정은 단순히 before_destroy 훅을 모델에 추가합니다. 이 기능이 없으면 모델 레코드를 파괴 할 때 다른 모델이 영향을받지 않습니다. – Kevin