How to query records that have an ActiveStorage attachment?

前端 未结 3 815
深忆病人
深忆病人 2020-12-18 21:02

Given a model with ActiveStorage

class User 
  has_one_attached :avatar
end

I can check whether a single user has an avatar



        
3条回答
  •  我在风中等你
    2020-12-18 21:37

    I wanted to know if a record has any attachments (I had multiple attachments say a passport and other docs for User) so I can display/hide a section in UI.

    Based on the answer here I've been able to add the following method to ApplicationRecord:

    def any_attached?
      ActiveStorage::Attachment.where(record_type: model_name.to_s, record_id: id).any?
    end
    

    Then you can use it like:

    User.last.any_attached?
    #=> true
    

提交回复
热议问题