【问题标题】:Rails: Delete records created before adding dependant: :destroyRails:删除添加依赖项之前创建的记录::destroy
【发布时间】:2021-03-05 22:39:15
【问题描述】:

有没有什么有效的方法可以删除在添加依赖项之前创建的所有关联记录::destroy ??

Class User
end

Class Post
  belongs_to :user, dependent: :destroy
end

在添加此依赖项之前创建的先前记录: :destroy 仍然存在并且 user_id 存在。 例如。

Post.first.user_id = 1

但 ID 为 1 的 User.first 在添加依赖项之前已经被销毁:: 销毁。 如何查找和删除这些 Post 记录???

【问题讨论】:

  • Post.where.not(user_id: User.select(:id))

标签: ruby-on-rails


【解决方案1】:
Post.where("NOT EXISTS(select 1 from #{User.table_name} where #{Post.table_name}.user_id=#{User.table_name}.id)").delete_all

这应该删除所有关联用户不再存在于数据库中的帖子。 如果您想在删除它们之前触发每个 Post 的回调,请改用 destroy_all。

请参阅:delete_all vs destroy_all? 了解区别。

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 2021-11-06
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多