开发者

Listing the names of associated models

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?


You want ActiveRecord::Reflection::ClassMethods#reflect_on_all_associations

So it would be:

 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)

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜