【发布时间】:2019-03-24 16:04:42
【问题描述】:
我正在使用has_ancentry gem,我希望类别计数是这种格式
“技术/笔记本电脑 (50)”
其中“技术”是父类别。 “笔记本电脑”是子类别,“50”是我分组查询的计数
categories = Category.joins(:products)
.where(products: {id: @products})
.group(:id, :name)
.count
问题是这样我只能得到子类别的“ID”。如果我要检索“父”类别,我必须拥有活动记录对象(因为在 has_ancestry 中 .parent() 是一个方法对象而不是数据库列)
型号
class Category < ApplicationRecord
has_ancestry
has_many :products, dependent: :destroy
类别
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ancestry"
t.index ["ancestry"], name: "index_categories_on_ancestry"
end
【问题讨论】:
-
请更新您的帖子,包括模型和关联。我们需要更多信息来解决问题,
-
完成。我添加了类别模型。
-
请添加实际架构而不仅仅是模型,因为最终您应该有某种 id 来获取子产品
-
完成。这是一个经典的 has_ancestry 表
标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord