Search code examples
ruby-on-railsrails-activestorage

How to get list of ActiveStorage attributes (attachment names)?


For example I have model

class User < ApplicationRecord
  has_one_attached :avatar
  has_one_attached :diploma

  has_many_attached :photos
  has_many_attached :files
end

How to get lists of attachments names for some model (separately for has_one_attached and has_many_attached)?

[:avatar, :diploma] and [:photos, :files] in this case.


Solution

  • A solution that doesn't depend on naming conventions and will give you exactly what you need based on Rails own internals:

    • for has_one_attached
    User
      .reflect_on_all_attachments
      .filter { |association| association.instance_of? ActiveStorage::Reflection::HasOneAttachedReflection }
      .map(&:name)
    
    • for has_many_attached
    User
      .reflect_on_all_attachments
      .filter { |association| association.instance_of? ActiveStorage::Reflection::HasManyAttachedReflection }
      .map(&:name)