我的實驗室模型:導軌 - 連接表刪除
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
解決了這個問題,但我不知道是否有一種方法可以建立關聯,所以我不用寫額外的代碼。
明確#delete和#destroy之間的區別。你可能想要#destroy。另外,如果你摧毀了一個實驗室,那麼它聽起來像你希望ChainOffers也被銷燬,然後任何要約 - 不要求其他ChainOffers(鏈接到不同的實驗室)也被銷燬? –