如何找到模型的关系? [英] How can I find a model's relationships?

查看:19
本文介绍了如何找到模型的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,当给定一个特定模型时,返回与其关联的所有相关模型.例如:

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?

推荐答案

Dog.reflect_on_all_associations

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

您不会在实例上执行此操作,而是在模型本身上执行此操作.

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

这篇关于如何找到模型的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆