Listing the names of associated models

前端 未结 1 1056
抹茶落季
抹茶落季 2021-02-01 01:55
class Article < ActiveRecord::Base
  has_many :comments
  belongs_to :category
end

Is there a class method for Article with which I can retrieve a l

相关标签:
1条回答
  • 2021-02-01 02:14

    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 讨论(0)
提交回复
热议问题