You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在自关联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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:50:17