下面是实现父子分类的代码:
migrate:
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.integer :parent_id
t.string :name
t.timestamps null: false
end
end
end
model:
class Category < ActiveRecord::Base
has_many :sub_categories, class_name: "Category", foreign_key: "parent_id", dependent: :destroy
belongs_to :parent_category, class_name: "Category", foreign_key: "parent_id"
end
查询语句:
categories = Category.includes(:sub_categories).where(parent_id: nil)
控制台返回的 SQL:
Category Load (1.5ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" IS NULL
Category Load (1.8ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" IN (1, 5)
Category Load (1.9ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 2]]
Category Load (1.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 3]]
Category Load (1.3ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 4]]
Category Load (1.3ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 6]]
Category Load (1.0ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 7]]
Category Load (1.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."parent_id" = ? [["parent_id", 8]]
发现会为子分类再查询一遍子分类,控制台返回的 SQL 语句从第 2 行之后,都是无用的。
另外数据是要最终渲染成 API 提供的 json 数据。
哪位同学有好的解决办法?