issue in order clause and limit in active record

柔情痞子 提交于 2019-12-11 03:46:59

问题


I am triggering this query

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

So the questions are:

  1. Why there is no order clause in the actual query?
  2. Why @relevant_customers_for_total_spent.count is greater than relevant_customers_count_for_total_spent. It should be equals to or less than.

*Update -1 *

I got the second issue:

@relevant_customers_for_total_spent.length 

is the right way to count the number of elements.

Update - 2

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.


回答1:


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

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?

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.

Update

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

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


来源:https://stackoverflow.com/questions/10597135/issue-in-order-clause-and-limit-in-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!