【问题标题】:Rails Ancestry Gem: how to write scope to match all parentsRails Ancestry Gem:如何编写范围以匹配所有父母
【发布时间】:2017-07-23 03:25:11
【问题描述】:

使用 Rails ancestry gem , 在 User 模型上编写范围以查找所有具有孩子/哪些是父母的记录的最佳方法是什么?

class User < ActiveRecords::Base
  has_ancestry

   def is_manager?
     has_children
   end

   scope :is_manager, -> { ... ? ... }

end

【问题讨论】:

  • 只有一个用户树吗? (是否有多个节点以 nil 作为祖先)。树有多大(~ 节点数,深度),有多少棵树?
  • 假设有多个树,每个树中都有数千条记录——例如SaaS 应用程序中公司的组织结构图

标签: ruby-on-rails ruby ancestry


【解决方案1】:

试试这个,我认为这是最好的方法

scope :is_manager, -> {where(id: User.pluck(:ancestry).compact.map { |e| e.split('/') }.flatten.uniq)}

它从数据库中仅选择祖先字段,删除nil,将其拆分并取数字,将其展平,使其成为uniq,然后根据它选择所有用户。

也可以查看question

【讨论】:

  • 您可能想在pluck 之前添加distinct。不过取决于数据库。
  • 这样做的缺点是它将数据库中的每个用户都加载到内存中。@icemelt 有更好的解决方案吗?
【解决方案2】:

与 icemelt 的答案相同..

这也是一样的,但它不是将所有记录从数据库加载到内存中,而是只选择唯一的祖先并处理它们——这在内存影响方面应该会有所不同

scope :is_manager, -> { where(id: User.select(:ancestry).distinct.pluck(:ancestry).compact.map { |x| x.split('/') }.flatten.uniq) }

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多