首页 > 解决方案 > 如何获取多态关联中所有类型的关联表的列表?

问题描述

假设,我们有表 Commentable,它commentable_id本质commentable_type上是多态的。基于此,我们如何获得所有关联表的列表/所有可能commentable_type的关联?

标签: ruby-on-railsruby-on-rails-5associationspolymorphic-associations

解决方案


检查您的模型的comments关系。我假设每个值得称道的模型都有很多comments.

ApplicationRecord.descendants.select { |klass| klass.reflections['comments'] }

或者您可以选择一个不同的字段Commentable.distinct(:commentable_type).pluck(:commentable_type),此查询返回一个类型数组(作为字符串)。每种类型都是模型名称,知道它们您可以推断出表名称。


推荐阅读