Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ActiveStorage: select all record with an attachment #32295

Closed
MittchoBaroco opened this issue Mar 19, 2018 · 3 comments
Closed

ActiveStorage: select all record with an attachment #32295

MittchoBaroco opened this issue Mar 19, 2018 · 3 comments

Comments

@MittchoBaroco
Copy link

Is there a way via a scope to only select all records with an attachment?

System configuration

Rails version: 5.2.0.rc1

Ruby version: 2.5

@georgeclaghorn
Copy link
Contributor

georgeclaghorn commented Mar 19, 2018

Join against the attachment association:

# Assuming a model defined like so:
class Post < ApplicationRecord
  has_one_attached :image
end

# ...you can join against :image_attachment to select posts having attached images:
Post.joins(:image_attachment).where('published_at >= ?', Time.now)

In the future, please ask usage questions on the rubyonrails-talk mailing list or on Stack Overflow. We reserve the issue tracker for bugs.

@MittchoBaroco
Copy link
Author

Thank you very much, sorry

@lucascaton
Copy link
Contributor

In case anyone is looking for a way to join against the active_storage_blobs table, this can be achieved by with the *_blob (like image_blob) association.

Here's an example that sum how many bytes are used by the attachments:

Post.joins(:image_blob).sum("active_storage_blobs.byte_size")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants