ruby-on-rails 如何在活动记录中删除(解除关联)关系而不删除

ckocjqey  于 5个月前  发布在  Ruby
关注(0)|答案(3)|浏览(71)

假设以下模型:

class Thing
  has_many :whats
end

class What
  belongs_to :thing
end

字符串
有一个特殊的Thing,我想解除所有whats与它的关联,但我不想删除/销毁whats。我只需要What.thing = null

jfewjypa

jfewjypa1#

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

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

字符串

ndh0cuux

ndh0cuux2#

更有效的做法是:

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

字符串

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

d7v8vwbk

d7v8vwbk3#

一个非常有效的选项是update_all。这将运行一个查询来更新记录,并且不会在内存中示例化数据库中的所有记录。但是,请注意,update_all不会对模型执行任何回调,也不会更新时间戳字段。但这似乎不是必需的。

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

字符串

相关问题