5
7

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.

ActiveRecord::Relationのcountの振る舞い

Last updated at Posted at 2015-07-07

問題点

ActiveRecord::Relationはmapやselect, eachなどのArray, Hash等で使えるメソッドをカバーしてくれています。のでcountもArray同様の振る舞いを行ってくれると思って、ブロックを渡すと…

User.create(name: 'hoge')
User.all.count { |user| user.name == 'fuga' }
=> 1
array = ['hoge']
array.count { |name| name == 'fuga' }
=> 0

こうなります。ActiveRecord::Relationではcountメソッドが条件判断をよしなにしてくれないのです。
※User.all.countという流れがありえんというツッコミは止めて下さい死んでしまいます

解決

なので先にwhereを噛まそうねという話

User.create(name: 'hoge')
User.where(name: 'fuga').count 
=> 0

処理が複雑になってくると、何処までがActiveRecord::Relationなのがこんがらがることがあるので、注意したいのでした

5
7
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
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?