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

发布于 2024-08-16 19:40:20 字数 366 浏览 2 评论 0原文

有没有办法找出模型有哪些关联?以这两个模型为例:

class Comment < ActiveRecord::Base
  belongs_to :commentable
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

我正在寻找类似的东西:

Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']

Is there a way to find out what associations a model has? Take these 2 models:

class Comment < ActiveRecord::Base
  belongs_to :commentable
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

I'm looking for something like:

Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

万人眼中万个我 2024-08-23 19:40:20

您正在寻找 reflect_on_all_associations

简而言之:

Post.reflect_on_all_associations(:has_many)

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

You're looking for reflect_on_all_associations.

So in short:

Post.reflect_on_all_associations(:has_many)

...will give an array (of object with attributes like name, etc) of all has_many associations.

枉心 2024-08-23 19:40:20

下面将列出特定 Post 实例的所有关联。

#app/models/post.rb
  def list_associations
    associations = []
    User.reflect_on_all_associations.map(&:name).each do |assoc|
      association = send assoc
      associations << association if association.present?
    end
    associations
  end

The following will list all the associations for a particular instance of Post.

#app/models/post.rb
  def list_associations
    associations = []
    User.reflect_on_all_associations.map(&:name).each do |assoc|
      association = send assoc
      associations << association if association.present?
    end
    associations
  end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文