2016-09-23 13 views
0

マイラボモデル:Railsの - 結合テーブルの削除

class Lab < ApplicationRecord 
    has_many :chain_offers, dependent: :delete_all 
    has_many :offers, through: :chain_offers 

モデル(chain_offers)に参加マイ

class ChainOffer < ApplicationRecord 
    belongs_to :lab 
    belongs_to :offer 

私のオファーモデル

class Offer < ApplicationRecord 
    has_many :chain_offers 
    has_many :labs, through: :chain_offers 

私はラボを削除しようとすると、それを削除を取得すると、ChainOfferテーブルのレコードも削除されますが、Offer.all.countをチェックすると、削除前と同じカウントになります。

はこう:

place = Place.find(place_id) 
place.offers.each do |offer| 
    offer.destroy 
end 
place.destroy 

は、その問題を解決するが、私は、追加のコードを記述する必要はありませんので、関連付けを設定する方法がある場合、私は思っていました。

+0

#deleteと#destroyの違いを明確にしてください。あなたはおそらく#destroyしたいです。 また、ラボを破壊すると、ChainOffersも破壊されたように見えますが、その後、他のChainOffers(別のLabsにリンクしているもの)も破壊される必要がありますか? –

答えて

1

多対多リレーションシップがどのように機能するかについての理解は、単に間違っています。私たちはどこPatient.find(1).destroyで患者を削除する場合

class Patient < ApplicationRecord 
    has_many :appointments, dependent: :destroy 
    has_many :doctors, through: :appointments 
end 

class Appointment < ApplicationRecord 
    belongs_to :patient 
    belongs_to :doctor 
end 

class Doctor < ApplicationRecord 
    has_many :appointments 
    has_many :doctors, through: :appointments 
end 

が、それはまたappointments.patient_id = 1appointments上の任意の行を削除する必要があります

は、この例を取ることができます。

doctorsテーブルの行を破棄しないでください!それは他の患者から医者を取り除き、あなたが望むものではありません。

+0

それは正しいです。私はこのように使用していないので、多対多ではないとして私の関係について考えていましたが、なぜ私はこれを最初のように設定したのか忘れました。明確な説明をありがとう! – Ancinek

関連する問題