Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

ruby on rails - How to query records that have an ActiveStorage attachment?

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?

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)

And if so, where is this documented?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Convention for attachment association names

Attachment associations are named using the following convention:

<NAME OF ATTACHMENT>_attachment

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

Querying for Active Storage attachments

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

For example, given the User class below

class User
   has_one_attached :avatar
end

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

User.joins(:avatar_attachment)

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

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...