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
なんだか冗長だ。