1
0

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 1 year has passed since last update.

【Rails】countメソッドにカラムを指定してエラーを回避

Posted at

環境

Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16

状況

relationでjoinしているpostscountしたら下記のエラーが発生し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

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?