【发布时间】:2016-11-07 10:49:31
【问题描述】:
# == Schema Information
#
# Table name: posts
#
# title :string
# published :boolean
#
执行 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}
cmets 表中的相同函数
# == 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 "cmets"."created_at" DESC 是在哪里生成的?如果我们将此列添加到组中,将得到无异常的结果! 感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord