【问题标题】:Get all record without attachment获取所有不带附件的记录
【发布时间】:2019-09-23 06:30:07
【问题描述】:

给定一个带有 ActiveStorage 的模型

class Report
  has_one :report_file
end

class ReportFile
  belongs_to :report
  has_one_attached :file
end

如何获取所有 ReportFile 中未附加文件的报告。

【问题讨论】:

    标签: ruby-on-rails ruby rails-activestorage


    【解决方案1】:

    Rails 5 中有 left_joins 方法,因此您可以使用它来代替 includes(或 eager_load,在此以相同的方式工作),因为它更适合这种情况。此外,您真正应该加入的表是active_storage_attachment,它与file_attachment 关联到ReportFile。因此,我认为得到你想要的最好的方法是:

    Report.left_joins(report_file: :file_attachment).where(active_storage_attachments: { id: nil })
    

    【讨论】:

      【解决方案2】:

      附件关联具有以下命名约定:_attachment。在您的情况下,这将是 file_attachment。

      由于这是一个常规的 ActiveRecord 关联,您可以使用它进行连接。那么,您要查找的查询是:

      Record.where(id: RecordFile.where.not(id: RecordFile.joins(:file_attachment)).pluck(:record_id)) 
      

      【讨论】:

        【解决方案3】:
        Report.joins("left join report_files on reports.id = report_files.report_id").where("report_files.file is null")
        

        会起作用

        【讨论】:

          【解决方案4】:
          Report.eager_load(:report_file).where(report_file: {file: nil})
          

          应该工作

          【讨论】:

          • report_files 查询中的表名
          • 不行,report_files 表中没有file 这样的列。
          • 同意。想法更倾向于使用“包含”,我们可以根据 activestorage 生成的列更改 where 条件
          【解决方案5】:

          Report.includes(:report_files).where('report_files.file= ?',nil)

          参考: https://apidock.com/rails/ActiveRecord/QueryMethods/includes

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-11-14
            • 2017-05-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多