Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

PIVOTAL LABS
07/27/12: ActiveRecord.count changes your select

Interestings

  • Chrome slow after click on body

While investigating memory leaks in a single page JS app, we found that rendering times increased by ~2 seconds after clicking on the body of the document.

It only happens in Chrome, Webkit and Firefox don’t have the problem.

We don’t seem to have any click handlers that fire when clicking on the body.

  • Putting .count on the end of an ActiveRecord query blows away your select

Here’s a scope for customers who have at least one subscription:

Customer.select(’DISTINCT customers.*’).joins(:subscriptions).where(”subscriptions.customer_id IS NOT NULL”)

This produces the following SQL:

SELECT DISTINCT customers.* FROM “customers” INNER JOIN “subscriptions” ON “subscriptions”.”customer_id” = “customers”.”id” WHERE (subscriptions.customer_id IS NOT NULL)

Say you want to know how many of these there are. If you put .count on the end of the scope, it converts the SQL to this:

SELECT COUNT(*) FROM “customers” INNER JOIN “subscriptions” ON “subscriptions”.”customer_id” = “customers”.”id” WHERE (subscriptions.customer_id IS NOT NULL)

It loses the distinct, so the query returns a customer object for each subscription. This means that if a customer has 2 subscriptions, they appear twice in the result set.

Workaround:

Using length instead of count works. It executes the query and then counts the number of results. There seems to be no easy way to do a count query that is not count(*).

This is a known bug in rails that has been patched, but not yet released:
https://github.com/rails/rails/issues/5554

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *