如何在不删除 Active Record 的情况下删除(取消关联)关系

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

假设以下模型:

class Thing
  has_many :whats
end

class What
  belongs_to :thing
end

有一个分词 Thing,我想解除所有 whats 与它的关联,但我不想 delete/destroy whats。我只需要 What.thing = null.

终端中的一个简单解决方案是 运行 控制台,遍历所有 Whats 并将 thing_id 更新为 nil

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

更有效的做法是:

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

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