Rails polymorphic has many through 多态双向关联配置求助
多态关联配置方案
前置校验
首先确认resource_topics表包含以下必填字段:
topic_id:关联主题表的外键topical_id:多态关联资源的主键topical_type:多态关联资源的模型类名
各模型关联配置
1. ResourceTopics 中间表模型
class ResourceTopics < ApplicationRecord belongs_to :topic belongs_to :topical, polymorphic: true end
2. Podcast、Post 资源模型
class Podcast < ApplicationRecord # 关联中间表,指定多态别名 has_many :resource_topics, as: :topical # 透过中间表关联主题 has_many :topics, through: :resource_topics end class Post < ApplicationRecord # 和Podcast配置逻辑一致 has_many :resource_topics, as: :topical has_many :topics, through: :resource_topics end
3. Topic 主题模型
class Topic < ApplicationRecord has_many :resource_topics # 关联播客资源:指定多态源为topical,源类型为Podcast类名 has_many :podcasts, through: :resource_topics, source: :topical, source_type: 'Podcast' # 如需支持查询关联文章,可新增对应配置 has_many :posts, through: :resource_topics, source: :topical, source_type: 'Post' end
可选优化(推荐)
给中间表加联合索引提升查询性能,迁移示例如下:
create_table :resource_topics do |t| t.bigint :topic_id, null: false t.bigint :topical_id, null: false t.string :topical_type, null: false t.timestamps end # 避免重复关联,同时加速主题维度的资源查询 add_index :resource_topics, [:topic_id, :topical_type, :topical_id], unique: true # 加速资源维度的主题查询 add_index :resource_topics, [:topical_type, :topical_id]
配置完成后即可正常使用需求提到的两个查询语法:
Podcast.first.topics返回对应播客关联的所有主题Topic.first.podcasts返回对应主题关联的所有播客
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

