rails方法获取模型的关联名称

Die*_*zar 32 activerecord ruby-on-rails

有没有办法找出模型的关联?拿这两个型号:

class Comment < ActiveRecord::Base
  belongs_to :commentable
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

我正在寻找类似的东西:

Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']
Run Code Online (Sandbox Code Playgroud)

rfu*_*duk 73

你在找reflect_on_all_associations.

简而言之:

Post.reflect_on_all_associations(:has_many)
Run Code Online (Sandbox Code Playgroud)

...将给出name所有has_many关联的数组(具有类似属性的对象).