mansoor.khan
mansoor.khan

Reputation: 2616

Ruby on Rails: Count records returned by find_by* methods

I read about the difference in usage of size, count and length here. It makes sense when I use it like this:

@posts = Post.all

puts "length: ", @posts.length 
puts "count: ", @posts.count # Makes a database call to count records
puts "size: ", @posts.size

All three returns the correct length. However, if I replace @posts = Post.all with @posts = Post.find_by(post_type: 'article') in the code snippet above, I get noMethodError errors for size, count and length for the post object #<Post:>

My questions:

Upvotes: 3

Views: 3698

Answers (3)

M. Karim
M. Karim

Reputation: 942

When you use Post.all it returns an ActiveRecord::Relation instance - that behaves very similar to Array. So you can do the Array operations like count, length or size with it.

But length selects all the records, loads into memory and counts as regular Array. So using it inefficient and discouraged.

But when you use find_by it returns first record matching the specified conditions. So, length, count or size wont work. you can read about it here.

If you want to fetch all the records that matches your query you better use where

Post.where(post_type: 'article').count

You can learn more about how to use the conditions here.

Upvotes: 6

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Why doesn't these methods work with find_by result?

find_by returns only the first matched record and you can't run .count on a object #<Post:>

You can use where for that purpose

Post.where(post_type: 'article').count

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51171

find_by method is intended to find only one record. You should use where instead:

Post.where(post_type: 'article').count

Upvotes: 3

Related Questions