Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 410
mechnicov Avatar asked Jun 06 '19 20:06

mechnicov


1 Answers

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)
like image 127
camilo.forero Avatar answered Sep 21 '22 18:09

camilo.forero