views:

175

answers:

1

I want to, when given a particular model, return all the related models it is associated with. For example:

class Dog < ActiveRecord::Base
  has_many :bones
  belongs_to :master
end

d = Dog.first
d.associations #<== should return [Bone, Master]

Is there a way to do this already without having to roll my own? Failing that, any suggestions for the best way to do this?

+10  A: 
Dog.reflect_on_all_associations

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#M001405

You wouldn't do this on an instance but on the model itself.

Matt Rogish
Great, couldn't find that for the life of me earlier. Just what I needed, thanks!
PJ