4

Taking the polymorphic associations example from rubyonrails.org and using the models below:

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

class Product < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

How do I go about finding the valid imageable_types?

E.g. so that it'd return: [:employee, :product]

pyepye
  • 156
  • 1
  • 6
  • 2
    There is this answer from 6 years ago http://stackoverflow.com/questions/2315239/finding-all-by-polymorphic-type-in-rails/2315469#2315469. What is does it loops over every model inside your project and using method reflect_on_all_associations looks for has_many or has_one associations. – Mirza Memic Jun 22 '16 at 20:50

1 Answers1

0

My question would be why do you need this? I'm not totally sure, but I think you may be looking for:

Picture.select(:imageable_type).distinct.pluck(:imageable_type)
oreoluwa
  • 5,553
  • 2
  • 20
  • 27
  • Your question is a good question... Maybe I'm setting up my models wrong... About your solution, it won't work for me because that would only return the `:imageable_type`s that were in use... I'm looking for _ALL_ types, whether in use, or _could_ be used. Ok, so like I said, maybe my models are set up wrong. In reality, what I have is a base `Report` which is polymorphic, and then concrete _reports_ (e.g. `ReportA`, `ReportB`, `ReportC`, etc.). What I want is the list of `Report*` that is defined so I can create a dropdown that selects the appropriate concrete report. – pyepye Jun 22 '16 at 21:09