获取没有附件的所有记录

Get all record without attachment

给定一个带有 ActiveStorage 的模型

class Report
  has_one :report_file
end

class ReportFile
  belongs_to :report
  has_one_attached :file
end

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

Report.eager_load(:report_file).where(report_file: {file: nil})

应该可以

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

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

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

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

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

在Rails5中有left_joins方法,所以你可以用这个代替includes(或eager_load,在这里用同样的方法),因为它更适合这种情况。此外,您真正应该加入以获得您想要的东西的 table 是 active_storage_attachment,它关联为 file_attachmentReportFile。因此,我认为获得所需内容的最佳方法是:

Report.left_joins(report_file: :file_attachment).where(active_storage_attachments: { id: nil })
Report.joins("left join report_files on reports.id = report_files.report_id").where("report_files.file is null")

会起作用