Rails 附加文件时的 ActiveStorage 范围

Rails ActiveStorage scope for when file is attached

使用 ActiveStorage 时,如何为附加文件创建范围。

例如:

class Check < ActiveRecord::Base
  has_one_attached :image
end

我想要 Check.has_attached_image 之类的东西 return 只记录存在附加图像的地方。

我知道 ActiveStorage 提供了一个 with_attached_image 范围。但这似乎不起作用:

irb(main):009:0> Check.with_attached_image.to_sql => "SELECT \"checks\".* FROM \"checks\""

范围 with_attached_image 的主要目的是避免 N+1 查询(在查询中包含附加的 blob)。

为了 return 只记录存在附加图像的地方,您可以在 Check 模型中创建一个范围,如下所示:

scope :has_attached_image, -> { joins(image_attachment: :blob) }

评论更新:

scope :has_attached_image, -> { joins(:image_attachment) }

这包括附件存在和不存在的范围:

class Check < ActiveRecord::Base
  has_one_attached :image

  scope :has_image, -> { joins(:image_attachment) }
  scope :missing_image, -> { where.missing(:image_attachment) }

end