ruby-on-rails - 如何获取多态关联中所有类型的关联表的列表?
问题描述
假设,我们有表 Commentable,它commentable_id
本质commentable_type
上是多态的。基于此,我们如何获得所有关联表的列表/所有可能commentable_type
的关联?
解决方案
检查您的模型的comments
关系。我假设每个值得称道的模型都有很多comments
.
ApplicationRecord.descendants.select { |klass| klass.reflections['comments'] }
或者您可以选择一个不同的字段Commentable.distinct(:commentable_type).pluck(:commentable_type)
,此查询返回一个类型数组(作为字符串)。每种类型都是模型名称,知道它们您可以推断出表名称。
推荐阅读
- python - 循环遍历列表中的多个字典,同时为增量变量赋值 - python
- python - 自动找到最佳自回归方法
- python-3.x - 如何通过时间可视化定量或定性的数据,但从不两者兼而有之?
- c++ - 如果 while 循环至少运行一次,那么执行代码的最有效方法是什么?
- bash - 如何通过 SSH 连接到启动启动 java 进程的 bash 脚本的服务器,然后在不终止脚本的情况下断开与服务器的连接?
- android - 使用 MockK 模拟改造接口返回 null
- vps - 如何在 VPS 上安全地部署 Fullstack 网站
- linux - 如何调用包含文件路径而不是文件路径末尾的文件的变量的字符串内容?重击/Linux
- javascript - 如何使用 instagram 基本显示 API 或 Graph API
- azure-active-directory - 如果用户存在于广告组中,如何让我的外观跳过?