6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails MySQLでthis is incompatible with sql_mode=only_full_group_by

Last updated at Posted at 2020-01-15

Group Byしたらエラーになった

akb_controller.rb
class AkbController < ApplicationController
  def index
    @idol = Akb.group(:area)
  end
end
# 実行されたSQL
SELECT `akb`.* FROM `akbs` GROUP BY `akbs`.`area`

# コンソールに出力されたエラー
Mysql2::Error: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'akimoto.akb.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

原因はMySQL5.7からデフォルトになったONLY_FULL_GROUP_BY

GROUP BYで使うカラムはSELECTでちゃんと指定しましょうよ。ということらしい。
参考:MySQL5.7にアップデートしたらonly_full_group_byでエラーになった

ということで修正。

hoge.rb
class AkbController < ApplicationController
  def index
    # .select(:area)を追加
    @idol = Akb.group(:area).select(:area) 
  end
end

なんだか冗長だ。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?