列出关联模型的名称 [英] Listing the names of associated models

查看:45
本文介绍了列出关联模型的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Article < ActiveRecord::Base
  has_many :comments
  belongs_to :category
end

是否有可以检索关联列表的文章类方法?通过查看模型的代码,我知道文章与评论和类别相关联.但是有没有办法以编程方式获取这些关联?

Is there a class method for Article with which I can retrieve a list of associations? I know by looking at the model's code that Article is associated to Comment and Category. But is there a method to get these associations programmatically?

推荐答案

你想要 ActiveRecord::Reflection::ClassMethods#reflect_on_all_associations

那就是:

 Article.reflect_on_all_associations

您可以传入一个可选参数来缩小搜索范围,因此:

And you can pass in an optional parameter to narrow the search down, so:

 Article.reflect_on_all_associations(:has_many)

 Article.reflect_on_all_associations(:belongs_to)

请记住,如果您想要所有模型名称的列表,您可以执行以下操作:

Keep in mind that if you want the list of all the names of the models you can do something like:

Article.reflect_on_all_associations(:belongs_to).map(&:name)

这将返回属于 Article 的所有模型名称的列表.

This will return a list of all the model names that belong to Article.

这篇关于列出关联模型的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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