I can’t seem to pull ordered data from the database. I’m trying to list users on my homepage based on how many views their profile has.
My users schema looks like this:
# == Schema Information
#
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# username :string(255)
# password_digest :string(255)
# views :integer
#
My controller:
class PagesController < ApplicationController
def home
@users = User.order("'views' DESC")
end
end
The problem is that .order does nothing at all. @users is still ordered by id, as if I had done User.all. I tried running User.order("'views' DESC") in the Rails console, but I get the same thing as User.all.
I checked the development.log and the query seems to have been executed correctly:
[1m[35mUser Load (0.2ms)[0m SELECT "users".* FROM "users" ORDER BY 'views' DESC
Rendered pages/home.html.erb within layouts/application (1.1ms)
Rendered layouts/_header.html.erb (0.5ms)
Rendered layouts/_footer.html.erb (0.0ms)
Doing the sorting client-sided works, however I want to paginate the users so this is not an option. Any advice would be greatly appreciated!
Check http://guides.rubyonrails.org/active_record_querying.html#ordering
For pagination you could get some help with this gem:
https://github.com/mislav/will_paginate