问题在活动记录为了条款和限制 [英] issue in order clause and limit in active record

查看:106
本文介绍了问题在活动记录为了条款和限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我触发此查询

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 " -------  "

更在日志中说,实际的查询解雇是:

More over log is saying the actual query fired is:

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. 为什么没有在实际的查询?
  2. 没有订单条款
  3. 为什么@ relevant_customers_for_total_spent.count大于relevant_customers_count_for_total_spent。它应该是等于或小于

*的更新-1 *

我得到了第二个问题:

@relevant_customers_for_total_spent.length 

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

is the right way to count the number of elements.

更新 - 2

我有一些客户ID阵列中的类似[2,3,4,5,6,75,56,57,58,59,60,61,62。我也就是在TOTAL_AMOUNT客户模型中的属性。我想rearrage在TOTAL_AMOUNT的(DESC)订单中所有的客户标识。我有另外一个因素,它指定的限制,即我有多少客户数量需要从该列表。一些事情一样,如果它的5所以,我需要前五名客户从基于TOTAL_AMOUNT的araay。

I have some customer ids in an array something like [2,3,4,5,6,75,56,57,58,59,60,61,62]. I have a attribute ie total_amount in Customer model. I want to rearrage all the customers ids in the order of total_amount (DESC). I have a another factor which specifies limit ie how many number of customers i need from that list. Some thing like if its 5. So I need top 5 customers from that araay based upon total_amount.

推荐答案

问题的关键是:阿雷尔是足够聪明,生成一个计数没有查询为了条款。

The point is: ARel is smart enough to generate a count query without order clause.

试想一下: #COUNT 相关收益 SELECT COUNT(*)... SQL查询,这反过来,返回一个数字 - ?为什么你会在这里需要什么下令

Just think of it: #count relation returns select count(*) ... SQL query, which, in turn, returns a single number - why would you need anything ordered here?

怪不得 #length 返回正确的号码。这是因为一个关系对象,在其 #length 被调用,不知道如何响应号召,引发自身返回结果的数据库,这通常是一个实例数组,然后委托调用到它的。因此,调用 #length 预期的元素个数数组回报的一个实例。

No wonder #length returns the correct number. That's because a relation object, on which #length is being called, not knowing how to respond to the call, triggers itself to return a result from DB, which is generally an instance of array, and then delegates the call down to it. Thus, calling #length on an instance of array returns expected number of elements.

更新

ids = [1,2,3,4,5]

Customer.where(id: ids).order('total_amount DESC').limit(5)

这篇关于问题在活动记录为了条款和限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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