Search code examples
ruby-on-railsrubyrails-activestorage

Get all record without attachment


Given a model with ActiveStorage

class Report
  has_one :report_file
end

class ReportFile
  belongs_to :report
  has_one_attached :file
end

How can I get all Report where file in ReportFile not attached.


Solution

  • There's left_joins method in Rails 5, so you can use this instead of includes (or eager_load, which works here in the same way), since it fits better in this case. Also, the table you really should join to get what you want is active_storage_attachment, which is associated as file_attachment to ReportFile. Thus, I think the best way to get what you want is:

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