【问题标题】:Mongoid - Get Children of ChildrenMongoid - 获取孩子的孩子
【发布时间】:2013-09-27 17:12:06
【问题描述】:

假设我有一个grandparent 文档,其中包含许多parents,并且每个parent 都有许多children

在带有 Mongoid 的 Rails 中,在不循环的情况下获取特定 grandparent 的所有 children 的最佳方法是什么?

例如,如果我要使用循环,它看起来像这样(粗略的代码):

  def children
    children = []
    parents.each do |p|
      p.children.each do |c|
        children << c
      end
    end
    children.uniq
  end

class Grandparent
  include Mongoid::Document
  has_many :parents
end

class Parent
  include Mongoid::Document
  belongs_to :grandparent
  has_many :children
end

class Child
  include Mongoid::Document
  belongs_to :parent
end

【问题讨论】:

  • “最佳”必须根据您的目的来定义。您是在优化性能、可读性、模块化还是具体什么?
  • @Mustafa Performance.

标签: ruby-on-rails mongoid


【解决方案1】:

像这样的方法,它会在调用后将children 作为属性加载。

def children(reload=false)
   @children = nil if reload
   @children ||= Child.where(:parent_id.in =>  parents.map(&:id))
end

也请参阅此 SO answer

【讨论】:

  • 这将返回 nil:children = Child.where(:parent_id.in =&gt; parents.map(&amp;:id)),但我的问题中的循环示例有效。
  • @James 如果您发布显示关联如何定义的模型文件会有所帮助。
  • @tihorn 添加到原始问题中。
  • @James 再试一次,在map 中从:id 更改为:_id。还添加了一个类似答案的参考问题。
  • @tihorn,我很尴尬。我正在使用rspec 对此进行测试,我的工厂正在建造中,但尚未创建。由于它们不在数据库中,因此调用 Child.where 将返回 nil,因为没有一个 children 被保存。
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
  • 2014-03-27
相关资源
最近更新 更多