環境
Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16
状況
relationでjoinしているposts
にcount
したら下記のエラーが発生しcount
できない。
posts = Post.joins(:users)
=>Post::ActiveRecord_Relation
posts.count
=>ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "AS"
解決法
ActiveRecordのcountメソッドは引数にカラムを指定できるのでそれを使うとcountできる。
posts = Post.joins(:users)
posts.count(:posts)
=> 4
参考