ActiveRecord group& count get error resoult

时间:2016-11-07 02:30:55

标签: ruby-on-rails ruby-on-rails-4 activerecord

# == Schema Information
#
# Table name: posts
#
#  title      :string
#  published  :boolean
#

exec Post.group(:title).count(:title)

irb(main):001:0> Post.group(:title).count(:title)
   (1.0ms)  SELECT COUNT("posts"."title") AS count_title, "posts"."title" AS posts_title FROM "posts" GROUP BY "posts"."title"
=> {"2"=>2, "4"=>1, "11"=>3, "3"=>1, "5324"=>1}

评论表中的相同功能

# == Schema Information
#
# Table name: comments
#
#  commentable_id   :integer
#  commentable_type :string
#  title            :string
#  body             :text
#  subject          :string
#  user_id          :integer          not null
#  parent_id        :integer
#  lft              :integer
#  rgt              :integer
#  is_name_hide     :boolean          default(FALSE)
#



   irb(main):001:0> Comment.group("commentable_id").count("commentable_id")
       (1.2ms)  SELECT COUNT("comments"."commentable_id") AS count_commentable_id, "comments"."commentable_id" AS comments_commentable_id FROM "comments" GROUP BY "comments"."commentable_id"  ORDER BY "comments"."created_at" DESC
    ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "comments.created_at" must appear in the GROUP BY clause or be used in an aggregate function
    LINE 1: ...s" GROUP BY "comments"."commentable_id"  ORDER BY "comments"...

exec Comment.group(“commentable_id”)。count(“commentable_id”)

  

收到错误消息,但 ORDER BY“comments”在哪里。“created_at”DESC 生成?如果我们在组中添加此列,将获得undecept结果!   感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我犯了一个错误

in

class Comment < ActiveRecord::Base
 default_scope { order :created_at => 'DESC' }
...
end

评论default_scope { order :created_at => 'DESC' }将按预期工作