Hikaru  Sakata
Hikaru Sakata

Reputation: 23

how to get all children models belonging to a certain parent model (Ruby on Rails)

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

Answers (1)

Erwin Schens
Erwin Schens

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

Related Questions