user1021325
user1021325

Reputation: 3

ActiveRecord not showing right records

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

Answers (2)

mu is too short
mu is too short

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

Alex Peattie
Alex Peattie

Reputation: 27637

Try:

@users = User.limit(10).order('name ASC')

Upvotes: 3

Related Questions