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

问题描述

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

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.

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

08-24 06:41