how to change the sort order for the collection?

22 views
Skip to first unread message

Zlodiak Zlodiak

unread,
Jun 25, 2015, 12:09:11 PM6/25/15
to rubyonra...@googlegroups.com
please help solve the problem.
tables:
users:
id: integer
name: varchar

posts:
id: integer
title: varchar
user_id: integer
views: integer


models:
User:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
end

Posts:
class Post < ActiveRecord::Base
belongs_to :user
end


controller:
def popular_diary
@diaries =
User.joins(:posts).group(:user_id).order('SUM(posts.views)')
end

the result @diaries contains a collection users, sorted by the number of
views. in ascending order (ASC). but I need to get a collection of
users, sorted in descending order (DESC).

I have tried to do so:
@diaries = User.joins(:posts).group(:user_id).order('SUM(posts.views)
:DESC')

but I got an error message:
SQLite3::SQLException: near ":DESC": syntax error: SELECT "users".* FROM
"users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" GROUP BY
user_id ORDER BY SUM(posts.views) :DESC

--
Posted via http://www.ruby-forum.com/.

Bayram Kuliyev

unread,
Jun 25, 2015, 12:38:38 PM6/25/15
to rubyonra...@googlegroups.com

DESC not :DESC. Remove semicolons.

Bayram Kuliyev

unread,
Jun 25, 2015, 12:38:44 PM6/25/15
to rubyonra...@googlegroups.com
order('SUM(posts.views) DESC').
Remove semicolons.

On Thursday, June 25, 2015 at 9:09:11 PM UTC+5, Ruby-Forum.com User wrote:

Zlodiak Zlodiak

unread,
Jun 25, 2015, 1:18:46 PM6/25/15
to rubyonra...@googlegroups.com
thanks! thanks!
Reply all
Reply to author
Forward
0 new messages