附加文件时的 Rails ActiveStorage 范围 [英] Rails ActiveStorage scope for when file is attached
问题描述
使用 ActiveStorage 时,如何为附加文件创建范围.
例如:
类检查
我想要像 Check.has_attached_image
这样的东西,只返回存在附加图像的记录.
我知道 ActiveStorage
提供了一个 with_attached_image
范围.但这似乎不起作用:
<代码>irb(main):009:0>Check.with_attached_image.to_sql=>"SELECT \"checks\".* FROM \"checks\""
范围 with_attached_image
的主要目的是避免 N+1 查询(在您的查询中包含附加的 blob).>
要仅返回存在附加图像的记录,您可以在 Check
模型中创建一个范围,如下所示:
scope :has_attached_image, ->{ joins(image_attachment: :blob) }
评论更新:
scope :has_attached_image, ->{ joins(:image_attachment) }
When using ActiveStorage, how do you create a scope for when files are attached.
For example:
class Check < ActiveRecord::Base
has_one_attached :image
end
I want something like Check.has_attached_image
to return only records where there is an existing attached image.
I know that ActiveStorage
provides a with_attached_image
scope. But that doesn't seem to be working:
irb(main):009:0> Check.with_attached_image.to_sql
=> "SELECT \"checks\".* FROM \"checks\""
Main purpose of the scope with_attached_image
is to avoid N+1 queries (to include the attached blobs in your query).
To return only records where there is an existing attached image, you can create a scope in the Check
model like this:
scope :has_attached_image, -> { joins(image_attachment: :blob) }
Update from comments:
scope :has_attached_image, -> { joins(:image_attachment) }
这篇关于附加文件时的 Rails ActiveStorage 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!