Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails get all associated classes of a polymorphic class

I have a polymorphic association like so (adapted from guides.rubyonrails.com):

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

  has_many :employees
end

Is there a way to get all of the possible :imageable_types only given the Picture model?

For example to get the class of has_many :quotes in the Product model, you would do:

Product.reflect_on_association(:employees).klass 

to get: # => Employee

Now I want to do something similar:

Picture.reflect_on_association(:imageable).klass 

This obviously throws an exception, but I want to get something like: # => [Employee, Product]

Is there a way to do this? (Without trying out all models to see if they contain has_many :pictures)

like image 949
dorilla Avatar asked Jan 16 '13 01:01

dorilla


1 Answers

I couldn't find a way to do this without looking at all the models, so I just adapted this solution: https://stackoverflow.com/a/2315469/1440599

like image 126
dorilla Avatar answered Dec 02 '22 03:12

dorilla