Here are my models:
class Left < ApplicationRecord
has_one :middle, dependent: :destroy
has_one :right, through: :middle
end
class Middle < ApplicationRecord
belongs_to :left, dependent: :destroy
belongs_to :right, dependent: :destroy
end
class Right < ApplicationRecord
has_one :middle, dependent: :destroy
has_one :left, through: :middle
end
I would like left.destroy to also destroy its middle and its right. Similarly I would like right.destroy to destroy its middle and its left.
With the setup above, right.destroy does what I want but left.destroy does not destroy its right.
However if I reverse the order of Middle's belongs_to declarations, right.destroy stops working and left.destroy starts working.
How can I get a left-middle-right association to be destroyed from either end?
Sure looks like a bug. Best I could figure is this rollback breaks the chain:
https://github.com/rails/rails/blob/v7.1.3/activerecord/lib/active_record/associations/belongs_to_association.rb#L12
Everything works fine from both directions, if that rollback isn't raised, which is why having your own callbacks works:
In case you want to try and patch the bug, here's my one attempt:
I only ran activerecord sqlite tests: