如何查询带有 ActiveStorage 附件的记录? [英] How to query records that have an ActiveStorage attachment?

查看:35
本文介绍了如何查询带有 ActiveStorage 附件的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有 ActiveStorage 的模型

Given a model with ActiveStorage

class User 
  has_one_attached :avatar
end

我可以检查单个用户是否有头像

I can check whether a single user has an avatar

@user.avatar.attached? 

但是,我如何返回包含(或所有没有)附件的所有用户的集合?

But how can I return a collection of all users with (or all users without) an attachment?

我尝试使用 joins 返回所有带有附件的用户,但这似乎不适用于 blob 或附件表,或者我的语法不正确.

I tried using joins to return all Users with an attachment, but this does not seem to work on either the blob or attachment table, or perhaps I'm not getting the syntax correct.

我确定我忽略了一些明显的东西.是否可以按照以下方式做一些事情:

I'm sure I am overlooking something obvious. Is it possible to do something along the lines of:

User.where(attached_avatar: nil)

如果有,记录在哪里?

推荐答案

附件关联名称约定

附件关联使用以下约定命名:

Convention for attachment association names

Attachment associations are named using the following convention:

<附件名称>_attachment

例如,如果您有 has_one_attached :avatar,则关联名称将为 avatar_attachment.

For example, if you have has_one_attached :avatar then the association name will be avatar_attachment.

既然您知道了附件关联的命名方式,您可以像使用任何其他 Active Record 关联一样使用 joins 来查询它们.

Now that you know how attachment associations are named, you can query them by using joins as you would any other Active Record association.

例如,给定下面的 User

For example, given the User class below

class User
   has_one_attached :avatar
end

您可以查询所有带有该附件的User记录,如下

You can query for all User records that have that attachment as follows

User.joins(:avatar_attachment)

这将执行一个 INNER JOIN,它只会返回带有附件的记录.

This performs an INNER JOIN which will only return records which have the attachment.

您可以像这样查询所有没有该附件的User记录

You can query for all User records that DO NOT have that attachment like this

User.
  left_joins(:avatar_attachment).
  group(:id).
  having("COUNT(active_storage_attachments) = 0")

这篇关于如何查询带有 ActiveStorage 附件的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆