Search code examples
ruby-on-railsactiverecord

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.


Solution

  • 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