所以我有两个这样的模特
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)