Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

:count yields wrong result #449

Open
NobodysNightmare opened this issue Aug 10, 2015 · 1 comment
Open

:count yields wrong result #449

NobodysNightmare opened this issue Aug 10, 2015 · 1 comment

Comments

@NobodysNightmare
Copy link

Reproduction

Model.create_100_entries
Model.page(1).per_page(10).count

Expected

=> 10

Actual

=> 100

Explanation

From an ActiveRecord perspective I am holding a Relation, that results in 10 records being returned. I don't understand, how the count for this relation could be higher.
Or to write it as rspec expectation:

relation = Model.page(1).per_page(10)
expect(relation.count).to eql relation.to_a.count

Workaround?

If (for some reason) this problem is not as easily solvable:
Is there a work around? The best solution I could find is calling to_a, which of course will perform the full SQL query.

@NobodysNightmare NobodysNightmare changed the title :count works counter-intuitively :count yields wrong result Aug 10, 2015
@joaozig
Copy link

joaozig commented Jun 6, 2016

When you use Model.count, ActiveRecord performs a SELECT COUNT, ignoring any limit parameter.

In this case, you can use:
relation = Model.page(1).per_page(10)
expect(relation.length).to eql(10)
or
relation = Model.page(1).per_page(10)
expect(relation.size).to eql(10)

.length will avoid another db query, but you must previously load the collection.
.size seems to be the best option because if the collection has already been loaded, it will return its length just like calling .length. If it hasn't been loaded yet, it's like calling .count.

you can read more about that here:
http://blog.hasmanythrough.com/2008/2/27/count-length-size
http://stackoverflow.com/questions/6083219/activerecord-size-vs-count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants