问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/259529/how-can-i-find-a-models-relationships