Skip to content

Instantly share code, notes, and snippets.

@voleinikov
Created January 30, 2013 04:17
Show Gist options
  • Save voleinikov/4670564 to your computer and use it in GitHub Desktop.
Save voleinikov/4670564 to your computer and use it in GitHub Desktop.
A simple example of how the magic of Active Record can sometimes be misused
# Length acts as an array method and gives the correct record count.
1.9.3-p362 :028 > u.clicks.select(:user_id).uniq.length
Click Load (0.4ms) SELECT DISTINCT user_id FROM "clicks" WHERE "clicks"."url_id" = 4
=> 2
# Here .count is being used by Active Record and inserted into the generated SQL and is not an array method. It gives a wrong answer.
1.9.3-p362 :029 > u.clicks.select(:user_id).uniq.count
(0.4ms) SELECT DISTINCT COUNT("clicks"."user_id") FROM "clicks" WHERE "clicks"."url_id" = 4
=> 3
# Correct use of .count via Active Record
1.9.3-p362 :027 > u.clicks.select("DISTINCT(clicks.user_id)").count
(0.4ms) SELECT COUNT(DISTINCT(clicks.user_id)) FROM "clicks" WHERE "clicks"."url_id" = 4
=> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment