使用 Rails ancestry
gem ,
在用户模型上编写范围以查找所有有子项/父项的记录的最佳方法是什么?
class User < ActiveRecords::Base
has_ancestry
def is_manager?
has_children
end
scope :is_manager, -> { ... ? ... }
end
最佳答案
试试这个,我认为这是最好的方法
scope :is_manager, -> {where(id: User.pluck(:ancestry).compact.map { |e| e.split('/') }.flatten.uniq)}
它只从数据库中选择 ancestry 字段,删除 nil,将其拆分并取数字,将其展平并使其唯一,然后根据它选择所有 User。
同时检查这个 question
关于ruby-on-rails - Rails Ancestry gem : how to write scope to match all parents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261210/