我有一个复杂的Category模型,它有parent_categories (它们是类别本身)。我想创建一个范围来查找所有三级类别(有父母的类别)。
class Category < ActiveRecord::Base
attr_accessible :title, :description, :parent_id, :category_image_attributes
has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy
belongs_to :parent_category, class_name: 'Category', foreign_key: 'parent_id'我将如何在ActiveRecord中实现这一点?
==更新==
所以我最终自己解决了这个问题,但我将把这个问题留给大家看看是否有更有效的方法来解决这个问题:
def self.all_third_level_categories
all_ids_of_categories_with_parents = Category.where("parent_id IS NOT NULL").map { |c| c.id }
Category.find_all_by_parent_id(all_ids_of_categories_with_parents)
end发布于 2013-11-05 22:26:15
扩展@bcd的注释,您提供的实现需要n-1查询才能获取深度为n的对象,这很快就会变得非常糟糕。
另一方面,在保存的地方,稍微有点开销
def set_level
self.level = parent_category.level + 1
end能把事情弄清楚。
https://stackoverflow.com/questions/19798540
复制相似问题