Rails - 连接表删除

时间:2016-09-23 10:24:15

标签: mysql ruby-on-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

如果我尝试删除Lab,它会被删除,ChainOffer表中的记录也会被删除,但在检查Offer.all.count后,计数仍然与删除前相同。

这样做的:

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

解决了这个问题,但我想知道是否有办法设置关联,所以我不必编写额外的代码。

1 个答案:

答案 0 :(得分: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患者的位置,则还应删除appointmentsappointments.patient_id = 1的所有行。

它不应该销毁doctors表上的任何行!这样可以将医生从其他患者身上移除,而不是你想要的。

相关问题