Reputation: 23
I am struggling with getting names of the Classes(Models) from a parent instance. Below is the situation;
<Parent>
has_many :child_a
has_many :child_b
<ChildA>
belongs_to :parent
<ChildB>
belongs_to :parent
I want to get what models the instance has like,
@parent = Parent.find(1)
@parent.hoge
=> [ChildA, ChildB] (ChildA & ChildB are class names)
Could you tell me if there is some method like above or some ways similar to that. I would appreciate your help!
Upvotes: 2
Views: 292
Reputation: 454
Parent.reflect_on_all_associations
This will return an array of ActiveRecord::Reflection
. From that you could just for example map the class name and constantize them for your class type via:
Parent.reflect_on_all_associations.map do |association|
association.options[:class_name].constantize
end
Upvotes: 1