2016-09-23 137 views
0

我的實驗室模型:導軌 - 連接表刪除

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(鏈接到不同的實驗室)也被銷燬? –

回答

1

您對多對多關係如何工作的理解完全不正確。

讓我們這個例子:

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 

如果我們在那裏與Patient.find(1).destroy刪除一個病人還應該刪除appointments任何行與appointments.patient_id = 1

它不應該破壞doctors表上的任何行!那會將醫生從其他患者身上移除,而不是你想要的。

+0

這是正確的。我在想我的關係不是多對多的,因爲我沒有這樣使用它,但是我忘記了爲什麼我把它放在首位。謝謝你明確的解釋! – Ancinek