読者です 読者をやめる 読者になる 読者になる

【rails】DBをPostgreSQLに変更するとcounter cultureが使えなくなったのでgemを修正

railsのDBがsqliteの時は、counter cultureでculture_fix_countsを普通に実行できていたが、DBをpostgresqlに変えると、以下のようなエラーが出るようになった。

irb(main):007:0> Picture.counter_culture_fix_counts 
PG::GroupingError: ERROR: column "albums.pictures_count" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: ...id, albums.album_id, COUNT(pictures.id) AS count, albums.pic... 
                                                             ^ 
: SELECT albums.album_id, albums.album_id, COUNT(pictures.id) AS count, albums.pictures_count FROM "albums" LEFT JOIN pictures AS pictures ON albums.album_id = pictures.album_id GROUP BY "albums"."album_id" ORDER BY "albums"."album_id" ASC LIMIT 1000 OFFSET 0 
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "albums.pictures_count" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: ...id, albums.album_id, COUNT(pictures.id) AS count, albums.pic... 
                                                             ^ 
: SELECT albums.album_id, albums.album_id, COUNT(pictures.id) AS count, albums.pictures_count FROM "albums" LEFT JOIN pictures AS pictures ON albums.album_id = pictures.album_id GROUP BY "albums"."album_id" ORDER BY "albums"."album_id" ASC LIMIT 1000 OFFSET 0

以下の通りに修正

修正対象ファイル

/home/hoge/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/counter_culture-0.1.34/lib/counter_culture.rb

修正箇所

変更前

while (records = counts_query.reorder(full_primary_key(klass) + " ASC").offset(start).limit(batch_size).group(full_primary_key(klass)).to_a).any?   

変更後

while (records = counts_query.reorder(full_primary_key(klass) + " ASC").offset(start).limit(batch_size).group(full_primary_key(klass),"#{klass.table_name}.#{column_name}").to_a).any?

以上