I'm working on a Rails 5.2 project and trying to groupan ActiveRecord::Relation
by a field in the table:
The below in the rails console returns an error:
2.4.0 :015 > Post.group(:published)
Post Load (3.9ms) SELECT `posts`.* FROM `posts` GROUP BY `posts`.`published` LIMIT 11
ActiveRecord::StatementInvalid: Mysql2::Error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'app_dev.posts.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by: SELECT `posts`.* FROM `posts` GROUP BY `posts`.`published` LIMIT 11
But, adding .sum()
runs correctly without an error...
> Post.group(:published).sum(:views)
Is there an apparent reason the first query would fail like that, and not the second?
In schema.rb
create_table "post", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
t.string "title", null: false
t.text "body", null: false
t.boolean "published", null: false, default: false
t.bigint "views", null: false, default: 0
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Thanks