如何查询附加了Active Storage且图像可变的记录?

use*_*745 1 activerecord ruby-on-rails rails-activestorage ruby-on-rails-6

如何查询所有附加图像的用户以及图像的位置.variable?

例如

我可以做这个

# controller

@users = User.all

Run Code Online (Sandbox Code Playgroud)

看法:


<% if user.image.attached? && user.image.variable? %>
<!-- display image -->
<% end %> 

Run Code Online (Sandbox Code Playgroud)

@users我想知道是否可以简单地只查询那些同时满足user.image.attached?和条件的逻辑,而不是在视图中包含该逻辑user.image.variable?

这可以通过某些 Active Record 查询实现吗?

tbu*_*ann 6

Active Storage 不提供您想要的快捷范围,但您可以提出自定义解决方案。

要仅获取带有附加图像的用户,请加入相应的附件:

User.joins(:image_attachment)
Run Code Online (Sandbox Code Playgroud)

附件(或者更确切地说: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})
Run Code Online (Sandbox Code Playgroud)

这应该是您想要的查询。此外,您可以将其作为范围,以便使用时更短:

# 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
Run Code Online (Sandbox Code Playgroud)