【问题标题】:Mixing acts_as_tree (ancestry gem), acts_as_list and default model scoping混合acts_as_tree(祖先gem)、acts_as_list 和默认模型范围
【发布时间】:2010-03-07 16:00:53
【问题描述】:

我正在使用ancestry gem 在树中构建一些组。同时,我使用acts_as_list 将组保持在排序列表中的同一树级别。给定以下模型:

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 在管理界面顶部生成面包屑导航。生成的 SQL 没问题,面包屑按树的深度排序。至少对于开发环境来说是这样。

在生产中它看起来完全不同:跟踪生成的 SQL 我发现不是祖先的 path 正在生成结果顺序,而是我的 default_scope 接管了。

所以我修复了我的模型,通过覆盖path 来忽略默认范围:

# remove default scope to not change path sorting
def path
  self.class.send :with_exclusive_scope do
    super
  end
end

但是,虽然这从我的 default_scope 开发中删除了位置范围,但它在生产中仍然被完全忽略。跟踪生产中的 SQL,我没有看到祖先的深度排序,而是从我的default_scope 看到的位置排序。

更新:由于我最初“修补”path 方法的想法有点愚蠢(敲敲:它不是继承的,它是动态定义的),我尝试了以下方法仍然无济于事:

# 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

开发中调用path时生成的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——但我认为这不是关键的区别。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-plugins named-scope


    【解决方案1】:

    acts_as_list 有一些 bugs 在处理 default_scope。您应该避免使用它或在 GitHub 上查找固定版本。试试this version(你可以在我之前链接的拉取请求中找到相关提交的链接)

    【讨论】:

    • 你建议用哪个 gem 来代替 rails 3 的acts_as_list?
    【解决方案2】:

    我在使用范围方法时遇到了类似的问题,我在祖先 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多