Gregg
Gregg

Reputation: 35864

How to remove (disassociate) relationship without delete in Active Record

Assuming the following models:

class Thing
  has_many :whats
end

class What
  belongs_to :thing
end

Having a particuler Thing, I want to disassociate all whats from it but I don't want to delete/destroy the whats. I just need What.thing = null.

Upvotes: 0

Views: 659

Answers (3)

justcode
justcode

Reputation: 417

A really efficient option is update_all. This would run 1 query to update the records and won't instantiate all the records in your db in memory. However, note that update_all will not execute any callbacks on the model and it won't update the timestamp fields. But it doesn't appear that's a requirement.

What.where(thing_id: @thing.id).update_all(thing_id: nil)

Upvotes: 0

danthedaniel
danthedaniel

Reputation: 469

More efficient would be to do:

What.joins(:thing).where(things: @thing).destroy_all

or

What.where(thing_id: @thing.id).destroy_all

Upvotes: 0

Yshmarov
Yshmarov

Reputation: 3729

A simple solution in the terminal would be to run the console, go through all the Whats and update the thing_id to nil

rails c
What.all.each do |what| what.update(thing_id: nil) end

Upvotes: 1

Related Questions