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.
A solution that doesn't depend on naming conventions and will give you exactly what you need based on Rails own internals:
has_one_attached
User
.reflect_on_all_attachments
.filter { |association| association.instance_of? ActiveStorage::Reflection::HasOneAttachedReflection }
.map(&:name)
has_many_attached
User
.reflect_on_all_attachments
.filter { |association| association.instance_of? ActiveStorage::Reflection::HasManyAttachedReflection }
.map(&:name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With