在Rails中,使用Mongoid,如何找到具有有效(非零)has_one引用的所有模型?

KDK*_*otU 8 ruby-on-rails has-one mongoid

所以我有两个这样的模特

class ModelParent
  include Mongoid::Document
  field :name, :type => String
  has_one :model_child
end

class ModelChild
  include Mongoid::Document
  field :name, :type => String
  belongs_to :model_parent
end
Run Code Online (Sandbox Code Playgroud)

假设我在rails控制台中有一个名为mp的持久化ModelParent实例

mc = mp.create_model_child(:name=>"child")
Run Code Online (Sandbox Code Playgroud)

然后呢

mp.model_child
Run Code Online (Sandbox Code Playgroud)

它返回一个有效的对象

但是,如果我这样搜索它:

ModelParent.where(:model_child.ne => nil).length
Run Code Online (Sandbox Code Playgroud)

它返回0

我已经尝试创建model_child然后使用build_model_child()进行分配,并且每个方法都显示model_child显然位于父级中,但是非nil(.ne)的查询无法找到所有带子级的ModelParents.

我究竟做错了什么?

更新:

回答我自己的问题.我仍然不确定为什么:model_child.ne => nil不起作用,但是......

我用这样的代码解决了这个问题:

  def self.with_child
    user_ids = ModelChild.all.only(:model_parent_id).map(&:model_parent_id)
    return ModelParent.where(:_id.in => user_ids).all
  end
Run Code Online (Sandbox Code Playgroud)

rub*_*ish 8

它不起作用,因为外键存储在属于关系的一侧.所以,在你的情况下,ModelChild集合将有一个字段,model_parent_id而不是相反.我猜你已经想出来了,但是我没有像你那样解决它,我建议你切换has_onebelongs_to关联然后使用:

 ModelParent.where(:model_child_id.ne => nil)
Run Code Online (Sandbox Code Playgroud)