5

を通じて、彼らはにhas_manyを使用して多対多の関係を示しています通じそうのように:の追加とhas_manyのから削除:Railsの団体ガイドから関係

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 

を:

@appo = @physician.appointments.find(1) 
@appo.destroy 

あなたが患者を破壊するとともに、予定のレコードを破棄したい場合は、あなたが追加する必要があります:has_manyのに設定依存:

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

関連する問題