基于具有has_many关联的子集合计数的查询始终显示没有结果 [英] Query based on a child collection count with has_many association is showing always no results

查看:67
本文介绍了基于具有has_many关联的子集合计数的查询始终显示没有结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于子集合中文档的数量进行查询.

I'm trying to base a query on the number of documents in the child collection.

这是我的情况:

class Pro
  include Mongoid::Document
  has_many :recommendations

  scope :lost, -> { where(:recommendation_ids => []) }
  scope :normal, -> { where(:recommendation_ids.ne => []) }
end

和子集合:

class Recommendation
  include Mongoid::Document

  belongs_to :pro
end

所以,现在我执行:

>> Pro.lost.count
0
>> Pro.all.select{|p| p.recommendations.count == 0}.count
1

我做错了什么?我也尝试过使用Pro.with_size(recommendation_ids: 0)和其他一些变体,但没什么新意.

What am I doing wrong? I've tried also with Pro.with_size(recommendation_ids: 0) and some other variations but nothing new.

任何想法都将受到高度赞赏,谢谢.

Any ideas would be highly appreciated, thanks in advance.

助力车2.0.1,Mongoid 4.0.0,Rails 4.0.6

Moped 2.0.1, Mongoid 4.0.0, Rails 4.0.6

推荐答案

我已经多次尝试找到解决此问题的方法,并且总是放弃.我只是知道如何轻松地模仿它.这可能不是一种非常可扩展的方法,但是它适用于有限的对象数.关键在于此文档中的一句话说:

I tried to find a solution for this problem several times already and always gave up. I just got an idea how this can be easily mimicked. It might not be a very scalable way, but it works for limited object counts. The key to this is a sentence from this documentation where it says:

返回条件对象的模型上的类方法也被视为作用域,也可以被链接.

Class methods on models that return criteria objects are also treated like scopes, and can be chained as well.

因此,您可以像这样定义类函数,而不是声明范围:

So, instead of declaring a scope you can define a class function like so:

def self.lost
  ids = Pro.all.select{|p| p.recommendations.count == 0}.map(&:id)
  Pro.where(:id.in => ids)
end

优点是,您可以在关联的(推荐)模型上进行各种查询,并返回满足这些查询的Pro实例(对我而言就是这种情况),而且最重要的是,您可以链接其他查询,例如所以:

The advantage is, that you can do all kinds of queries on the associated (Recommendations) model and return those Pro instances, where those queries are satisfied (which was the case for me) and most importantly you can chain further queries like so:

Pro.lost.where(:some_field => some_value)

这篇关于基于具有has_many关联的子集合计数的查询始终显示没有结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆