Ruby on Rails Thursday, June 25, 2015

order('SUM(posts.views) DESC').
Remove semicolons.

On Thursday, June 25, 2015 at 9:09:11 PM UTC+5, Ruby-Forum.com User wrote:
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/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/ef66b44c-52d3-4963-8b63-ff0835be32dc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment