Ancinek Ancinek - 2 months ago 8
MySQL Question

Rails - join table deletion

My Lab model:

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


My Join model (chain_offers)

class ChainOffer < ApplicationRecord
belongs_to :lab
belongs_to :offer


My Offer model

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


If I try to delete Lab, it gets delete, records in ChainOffer table are also deleted, but after checking
Offer.all.count
the count is still the same as before deletion.

Doing:

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


solves that problem, but I was wondering if there is a way to set up associations so I do not have to write additional code.

max max
Answer

Your understanding of how a many to many relationship works is simply incorrect.

Lets take this example:

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

If we where to delete a patient with Patient.find(1).destroy it should also delete any rows on appointments with appointments.patient_id = 1.

It should NOT destroy any rows on the doctors table! That would remove the doctor from other patients and is not what you want.