【问题标题】:Set names in self-join model在自连接模型中设置名称
【发布时间】:2013-03-16 19:11:30
【问题描述】:

我正在使用 AwesomeNestedSet gem 来填充类别树。

型号:

class Category < ActiveRecord::Base
 attr_accessible :name, parent_id
 has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id"
 belongs_to :parent_category, :class_name => "Category"
 acts_as_nested_set
end

我需要这样的名称输出集合:

Category_1
Category_1 >> Category_2
Category_1 >> Category_2 >> Category_3
Category_4

对 DB 进行最少计数查询的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord nested-attributes


    【解决方案1】:

    对不起,回答自己的问题....

    简单:

    def self.nested_names
        name = ""
        Category.each_with_level(Category.all) do |category, level|
          if category.root?
            name = category.name
          else
            name += " >> " + category.name
          end
          category.name = name
        end
      end
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 2021-04-15
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多