Reputation: 3
In Rails 3, when I write:
@users = User.limit(10).sort_by(&:name)
it is giving me 10 users in name order, but not the first 10 alphabetically like I want. What am I doing wrong?
Thanks!
Upvotes: 0
Views: 47
Reputation: 434585
The sort_by
method is from Enumerable. So, in order to call sort_by
, ActiveRecord has to retrieve the records from the database; ActiveRecord will first do this:
User.limit(10)
to get ten records from the database and then those records will be sorted (in Ruby) using their names. The end result is that the records will have been extracted from the database before they're sorted.
The solution is to listen to Alex Peattie and use the order
method.
Upvotes: 1