Rails
的 Category model
应用通过递归局部渲染而导致过多的数据库查询。
问题:什么是最佳做法?
以下示例:
view / categories / index.html.slim:
h1 Categories
ol
= render @categories.roots
view / categories / _category.html.slim:
li
= link_to category.name, category
- if category.children
ol
= render category.children
models / category.rb:
class Category < ApplicationRecord
belongs_to :parent, class_name: 'Category', optional: true
has_many :children, class_name: 'Category', foreign_key: :parent_id
scope :roots, -> { where parent_id: nil }
end