订单条款中的问题和活动记录中的限制

我正在触发此查询

p "my query starts here..." @relevant_customers_for_total_spent = Customer.order("total_amount DESC").where('id IN (?)',@customers_ids).limit(relevant_customers_count_for_total_spent) p " ------- " p relevant_customers_count_for_total_spent # output is: 1139 p @relevant_customers_for_total_spent.count # output is: 2888 p " ------- " 

更多的日志是说实际的查询是:

 SELECT COUNT(*) FROM `customers` WHERE (id IN (2,3,4,5,6,75,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,75,296,297,298,2889)) LIMIT 1139 

所以问题是:

  1. 为什么实际查询中没有order子句?
  2. 为什么@ relevant_customers_for_total_spent.count大于relevant_customers_count_for_total_spent。 它应该等于或小于。

* 更新-1 *

我得到了第二个问题:

 @relevant_customers_for_total_spent.length 

是计算元素数量的正确方法。

更新 – 2

我有一些像[2,3,4,5,6,75,56,57,58,59,60,61,62]这样的客户ID。 我在Customer模型中有一个属性,即total_amount。 我想按照total_amount(DESC)的顺序重新安装所有客户ID。 我有另一个因素指定限制,即我需要从该列表中有多少客户。 有些事情,比如它的5.所以我需要来自该araay的前5名客户,基于total_amount。

重点是:ARel非常聪明,可以在没有order子句的情况下生成count查询。

想一想: #count relation返回select count(*) ... SQL查询,反过来又返回一个数字 – 为什么你需要在这里订购任何东西?

难怪#length返回正确的数字。 这是因为调用#length的关系对象不知道如何响应调用,它会触发自己从DB(通常是数组的实例)返回结果,然后将调用委托给它。 因此,在数组实例上调用#length返回预期的元素数。

更新

 ids = [1,2,3,4,5] Customer.where(id: ids).order('total_amount DESC').limit(5)