Problems with limit method in Rails 3.2 and hash ordering

ぃ、小莉子 提交于 2019-12-25 06:57:55

问题


I have a database with cities which has_many :businesses

I want to display a list of 20 cities. These 20 cities should be the ones with the most businesses. Only if there are less than 20 cities with at least one business I add the cities with the most inhabitants to this list of 20 cities. Since the cities are ordered by inhabitants in my database I can simply take the first ones by id in this case.

My query now is:

popularcities = City.order("businesses_count desc").limit(20)

businesses_count is a column in my database with the number of businesses in the city.

Now, I get a list of 20 businesses ordered by businesses_count, those with the most businesses and the others (with no businesses) are the biggest, everything seems perfect.

As a last step I want to sort this list of 20 cities by "name asc". But if I do so Rails orders the whole list of cities in my database (>1.000) again, not just the list of 20. So the prior sorting by cities with the most businesses gets lost. If I inspect the local variable "popularcities" with a debugger before final sorting I get the correct hash of 20 entries.

How can I make sure Rails finally just orders my list 20 by "name asc", not again the whole database with all the cities?

Here is the relevant part of the code in my cities_controller:

popularcities = City.order("businesses_count desc").limit(20) #gives me a list with the cities I need
@cities = popularcities.order("name asc") #gives me a list of all >1.000 cities sorted by name

回答1:


Just use Ruby's native sort.

popularcities = City.order("businesses_count desc").limit(20)
@cities = popularcities.sort_by(&:name)


来源:https://stackoverflow.com/questions/9430201/problems-with-limit-method-in-rails-3-2-and-hash-ordering

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