如何查询附加了 Active Storage 且图像可变的记录?
How to query for records where Active Storage attached and image is variable?
如何查询所有附有图片的用户以及图片所在的位置.variable?
?
例如
我能做到
# controller
@users = User.all
查看:
<% if user.image.attached? && user.image.variable? %>
<!-- display image -->
<% end %>
我想知道我是否可以只查询满足 user.image.attached?
和 user.image.variable?
[=16= 条件的那些 @users
而不是在视图中具有该逻辑]
某些 Active Record 查询是否可行?
Active Storage 不提供您想要的快捷范围,但您可以提出自定义解决方案。
如果只获取有图片的用户,加入相应的附件:
User.joins(:image_attachment)
附件(或更确切地说:blob)是可变的,如果它的 content_type
出现在 ActiveStorage.variable_content_types
数组中,请参阅 https://github.com/rails/rails/blob/v6.1.3.2/activestorage/app/models/active_storage/blob/representable.rb#L42-L44。
所以我们可以进一步查询那个 content_type
,但是我们需要为此加入 blob(通过附件隐式地):
User.joins(:image_blob).where(active_storage_blobs: {content_type: ActiveStorage.variable_content_types})
这应该是您想要的查询。此外,您可以将其作为范围,以便在使用时更短:
# app/models/user.rb
scope :with_variable_image -> do
joins(:image_blob).where(active_storage_blobs: {content_type: ActiveStorage.variable_content_types})
end
# app/controllers/users_controller.rb or wherever
users = User.with_variable_image
如何查询所有附有图片的用户以及图片所在的位置.variable?
?
例如
我能做到
# controller
@users = User.all
查看:
<% if user.image.attached? && user.image.variable? %>
<!-- display image -->
<% end %>
我想知道我是否可以只查询满足 user.image.attached?
和 user.image.variable?
[=16= 条件的那些 @users
而不是在视图中具有该逻辑]
某些 Active Record 查询是否可行?
Active Storage 不提供您想要的快捷范围,但您可以提出自定义解决方案。
如果只获取有图片的用户,加入相应的附件:
User.joins(:image_attachment)
附件(或更确切地说:blob)是可变的,如果它的 content_type
出现在 ActiveStorage.variable_content_types
数组中,请参阅 https://github.com/rails/rails/blob/v6.1.3.2/activestorage/app/models/active_storage/blob/representable.rb#L42-L44。
所以我们可以进一步查询那个 content_type
,但是我们需要为此加入 blob(通过附件隐式地):
User.joins(:image_blob).where(active_storage_blobs: {content_type: ActiveStorage.variable_content_types})
这应该是您想要的查询。此外,您可以将其作为范围,以便在使用时更短:
# app/models/user.rb
scope :with_variable_image -> do
joins(:image_blob).where(active_storage_blobs: {content_type: ActiveStorage.variable_content_types})
end
# app/controllers/users_controller.rb or wherever
users = User.with_variable_image