How can I find a model's relationships?

 ̄綄美尐妖づ 提交于 2019-12-18 14:14:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!