Ruby on rails 在Rails中,使用Mongoid,如何找到所有具有有效(而非零)has_one引用的模型?
我有两个这样的模型Ruby on rails 在Rails中,使用Mongoid,如何找到所有具有有效(而非零)has_one引用的模型?,ruby-on-rails,mongoid,has-one,Ruby On Rails,Mongoid,Has One,我有两个这样的模型 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 假设我在rails控制台中有一个名为mp的
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
假设我在rails控制台中有一个名为mp的ModelParent持久化实例
mc = mp.create_model_child(:name=>"child")
然后呢
mp.model_child
它返回一个有效的对象
但是,如果我像这样搜索它:
ModelParent.where(:model_child.ne => nil).length
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
它返回0
我尝试过创建model_child,然后分配它,也使用build_model_child(),每个方法都显示model_child明显位于父级中,但是对not nil(.ne)的查询无法找到所有具有子级的modelparent
我做错了什么
更新:
回答我自己的问题。我仍然不确定:model_child.ne=>nil为什么不起作用,但是
我通过编写如下代码解决了这个问题:
ModelParent.where(:model_child.ne => nil).length
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
它不工作,因为外键存储在关系的“属于”端。因此,在您的情况下,
ModelChild
集合将有一个字段model\u parent\u id
,而不是相反。我想你已经明白了,但我建议你不要像你那样解决它,而是将有一个和属于关联,然后使用:
ModelParent.where(:model_child_id.ne => nil)
在这种情况下,我不会依赖.ne,我发现.ne方法并不总是很有效:
例如,尝试放置一个名为“false”的字符串,并尝试使用.ne;-)搜索它
我发现,对于这种情况,可靠地找到合适模型的最佳方法是使用原生Mongo$type
ModelParent.where(:model_child_id => { :$type => 7 })
在已知类型的列表下面,我发现这样可以更有效地查找格式错误的字段
- 双1
- 字符串2
- 对象3
- 阵列4
- 二进制数据5
- 未定义(已弃用)6
- 对象id 7
- 布尔值8
- 日期9
- 空10
- 正则表达式11
- JavaScript 13
- 符号14
- JavaScript(具有作用域)15
- 32位整数16
- 时间戳17
- 64位整数18
- 最小键255
- 最大键127
我找到了另一种方法,但我不知道是更有效还是更无效:您可以使用拒绝方法。
例如:
ModelParent.all.reject{ |r| r.model_child.nil?}