如何在自关联Category模型中合并分类集合与其父级记录
分类集合合并父级的优雅实现
模型定义
我们的Category模型采用自关联结构,支持分类嵌套:
class Category < ApplicationRecord belongs_to :parent, class_name: 'Category', foreign_key: :parent_id has_many :children, class_name: 'Category', foreign_key: :parent_id end
无父级的分类为顶级分类。
需求说明
给定一个分类集合,需要将其与对应的所有父级分类合并(当前业务场景最多一级子分类,但代码需兼容更深层级嵌套)。核心使用场景是简化关联逻辑,实现post.categories = categories.with_parents。
现有实现的问题
当前的实现方式不够优雅高效,需要先加载所有分类,再手动获取父级后去重:
post.categories = (categories + categories.map(&:parent)).compact.uniq
待优化的方案
尝试过以下方案,但逻辑合理性不足,希望找到基于join/union/merge的更优实现:
class Category < ApplicationRecord # ... def self.with_parents self.or(unscoped.where(id: select(:parent_id))) end end
内容的提问来源于stack exchange,提问作者Tom Lord
相关产品推荐
相关产品推荐

