【问题标题】:ActiveRecord to execute a single SQL statement to destroy based included dependent modelActiveRecord 执行单个 SQL 语句以销毁基于包含的依赖模型
【发布时间】:2020-01-21 22:55:48
【问题描述】:

假设我有一个 ActiveRecord 模型 Document,它与子依赖模型 File 具有 has_many 关系。我可以使用如下查询为给定的父 Document 急切加载文件:

document_with_files = Document.includes(:files).find_by(document_id: document_id)

如果同一 SQL 语句中只有一个子文件,ActiveRecord 中是否有删除父文档的方法?我已经尝试过类似以下的方法,并且非常接近:

Document.select("document.*, COUNT(files.id) file_count")
        .joins(:files)
        .group("document.id")
        .where(document_id: document_id_to_be_found)
        .where("file_count = ?", 1)

似乎我对file_count 的分配在最后的.where 子句中没有得到认可。

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord


    【解决方案1】:

    对于您的场景,以下代码可以找到只有一个子文件的文档。

    Document.joins(:files).group('documents.id').having('count(files.id) = 1')

    如果你想删除父文档,如果只有一个子文件作为同一 SQL 语句的一部分。

    Document.joins(:files)
            .group('documents.id')
            .having('count(files.id) = 1')
            .find_by(document_id: document_id_to_be_found)
            .destroy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      相关资源
      最近更新 更多