mithunm93 mithunm93 - 5 months ago 70
Ruby Question

ActiveRecord has_many through dependent :destroy issue

I have 3 models that are set up like this:

Class A
has_many class_b dependent :destroy
has_many class_c dependent :destroy
end

Class B
belongs_to class_a
has_many class_c through class_a conditions: proc {<conditions>} dependent :destroy
end

Class C
belongs to class_a
end

conditions: only a subset of the class_c objects that belong to class_a also belong
to class_b. class_c has a column that is essentially class_b_id, so only those
instances will be deleted.


I'm trying to destroy an instance of class_b, but I get this error:

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection (Cannot modify 'association ClassB#class_c' because the source reflection class 'ClassC' is associated to 'ClassA' via :has_many.)


What can I do to fix this error? Do I have to rework my associations?

Answer

I didn't want to change the fundamental associations in my codebase so what I ended up doing is removing the dependent: destroy from class_b's association with class_c and just writing a custom query in the before_destroy of class_b

Comments