ntonnelier
ntonnelier

Reputation: 1549

ActiveStorage::Attachment find resource by blob_id

I have the following model

class Document
  has_many_attached :previews
  ...
end

And I'm trying to find single elements there. The problem is if I do:

@document.previews.find_by(blob_id: 22)

I get this error: undefined method `find_by' for #<ActiveStorage::Attached::Many>

So I'm kind of forced to loop through enumerable:

@document.previews.find { |p| p.blob_id == 22 }

Is there any other (better/prettier) way to do this?

Upvotes: 1

Views: 3118

Answers (2)

Ron Shinall
Ron Shinall

Reputation: 71

@ntonnelier I have a similar model, and with Rails 7.0.3 your first example works fine for me:

@document.previews.find_by(blob_id: 22)

Another couple of options that work are:

@document.previews.where(blob_id: 22)
@document.previews.blobs.find_by_id(22)

Upvotes: 3

eugen
eugen

Reputation: 9226

You should be able to access the blobs for a particular record via the blobs method, which gets you an ActiveRecord collection, and you can use find on that one.

Something like @document.previews.blobs.find(22) might work in your particular case.

Upvotes: 0

Related Questions