我用的是
ancestry gem
在树中构造一些组。同时,我使用acts_as_列表将组保持在排序列表中的同一树级别。给定以下模型:
class Group < ActiveRecord::Base
acts_as_tree
acts_as_list :scope => "ancestry"
named_scope :parentable, :conditions => "NOT type = 'PriceGroup'"
named_scope :without, lambda { |ids| { :conditions => ['id NOT IN (?)', ids] }}
default_scope :order => "groups.position ASC, groups.name ASC"
end
这几乎达到了预期的效果(如
@group.path
在管理界面的顶部生成breadcrumb导航。生成的sql没问题,面包屑应该按照树的深度进行排序。至少在开发环境中是这样的。
在产品中,它看起来完全不同:跟踪生成的sql,我发现不是祖先的
path
正在生成结果顺序,但是
default_scope
接管。
所以我修正了我的模型,通过重写来忽略默认范围。
路径
:
# remove default scope to not change path sorting
def path
self.class.send :with_exclusive_scope do
super
end
end
但是当这把我的职责范围从
默认范围
在开发过程中,它在生产中仍然被完全忽略。跟踪生产中的sql,我看不到祖先的深度排序,而是从我的
默认范围
.
更新:
因为我最初的“修补”想法
路径
方法有点傻(敲打敲打:它不是继承的,是动态定义的),我尝试了以下操作仍然没有结果:
# remove default scope to not change path sorting
def path_with_exclusive_scope
self.class.send :with_exclusive_scope do
path_without_exclusive_scope
end
end
alias_method_chain :path, :exclusive_scope
打电话时
路径
在开发过程中,生成的sql如下:
SELECT *
FROM "groups"
WHERE ("groups"."id" IN (5,64))
ORDER BY (case when ancestry is null then 0 else 1 end), ancestry
与此相比,生产中生成的sql如下:
SELECT *
FROM `groups`
WHERE (`groups`.`id` IN (8,49))
ORDER BY groups.position ASC, groups.name ASC
开发使用sqlite,而生产使用mysql,但我不认为这是关键的区别。