导轨 - 连接表删除

问题描述:

我的实验室模型:导轨 - 连接表删除

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(链接到不同的实验室)也被销毁? –

您对多对多关系如何工作的理解完全不正确。

让我们这个例子:

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