Ancinek Ancinek - 1 year ago 87
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
the count is still the same as before deletion.


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

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 Source

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

class Appointment < ApplicationRecord
  belongs_to :patient
  belongs_to :doctor

class Doctor < ApplicationRecord
  has_many :appointments
  has_many :doctors, through: :appointments

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download