Rails - Select records where active storage link does not exist

444 views Asked by At

I am using rails active storage and I want to know if it is possible to create a scope where i can pull users who are missing the profile image

Suppose I have the following User model

class User < ApplicationRecord
  has_one_attached :avatar
end

I know I can check if the image is linked with the object via following

user.avatar.attached?

But what if I want to pull those users from database who are missing the avatar? I am sure there is a better way than pulling all users and looping through them to find the users who have no avatar

Any tip will be really appreciated.

1

There are 1 answers

1
Sid Biffi On

You can try to join and get all the user with avatar and subtract them to all users like that:

@no_avatar_users = User.all - User.joins(:avatar)