代码之家  ›  专栏  ›  技术社区  ›  hurikhan77

混合acts_as_tree(祖先宝石)、acts_as_list和默认模型范围

  •  4
  • hurikhan77  · 技术社区  · 16 年前

    我用的是 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,但我不认为这是关键的区别。

    2 回复  |  直到 11 年前
        1
  •  1
  •   Valentin Nemcev    15 年前

    acts_as_list 有一些 bugs 在处理默认范围时。您应该避免使用它,或者在github上查找固定版本。尝试 this version (您可以在我先前链接的请求中找到指向相关提交的链接)

        2
  •  0
  •   Miguelgraz    11 年前

    我在使用scope方法时遇到了类似的问题,我在祖先wiki上找到了这个。

      has_ancestry :cache_depth =>true
      acts_as_list :scope => 'ancestry = \'#{ancestry}\''
      named_scope :ordered, :order => "ancestry_depth,position DESC"
    

    https://github.com/stefankroes/ancestry/wiki/arrange_as_array

    推荐文章