避免使用递归局部的ROBAR

时间:2018-07-27 23:11:17

标签: sql ruby-on-rails activerecord

具有自引用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

0 个答案:

没有答案