Gal Ben-Haim
Gal Ben-Haim

Reputation: 17803

rails delete has_one :through association

I have the following data relationships:

model A has_one B, :through => C
model A has_one C, :dependent => :destroy

model B has_many C, :dependent => :destroy
model B has_many A, :through => C

model C belongs_to A
model C belongs_to B

let's say I have object a (type A) and object b (type B) and a.b = b, I want to remove the association.

what i'm currently doing is b.as.delete(@a), it removes the row from the C table, but a.b stays valid, even if I try to do a.b = nil it stays valid with the old value.

I just found out that if it happens only if I add the association by a.b = b if I add it by doing b.as << a, everything is working fine as expected when deleting..

what am I doing wrong ?

update - if i do a.reload the value is updated to nil also in the case i created the association with a.b = b, i don't want to use reload to get the correct value. why does it happen only in this case and not in the b.as << a case ?

Upvotes: 2

Views: 1310

Answers (1)

wpgreenway
wpgreenway

Reputation: 1719

The active record delete method only deletes the row of the object you are referencing, and does not respect your :dependent => :destroy relationship.

What you want to do is use the destroy method instead, and this will also propogate the destroy through as you have defined.

Upvotes: 1

Related Questions