rails/rails — pull request #5453 by JonRowe (2012-03-15 19:25:20+00:00)
Title: When Active Record has already loaded a unique association `.size` returns the wrong number.

When ActiveRecord has already eager loaded an association a call to that association returns the wrong number, count still returns correctly because it executes a fresh query. This may be undesirable. This patch respects the `:uniq` flag on the association and filters the already loaded array accordingly before calling `.size`.

Tested against SQLite, Mysql and Postgres (even though this modified no sql).

Fixes #4982 (symptoms shown below)

User.where(id:5).first.followers.size
User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1
User Load (0.3ms) SELECT DISTINCT `users`.* FROM `users` INNER JOIN `followers_users` ON `users`.`id` = `followers_users`.`user_id` WHERE `followers_users`.`follower_id` = 5

User.where(id:5).includes(:followers).first.followers.size
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1
SQL (0.8ms) SELECT `users`.*, `t0`.`follower_id` AS ar_association_key_name FROM `users` INNER JOIN `followers_users` `t0` ON `users`.`id` = `t0`.`user_id` WHERE `t0`.`follower_id` IN (5)
=> 18

See https://gist.github.com/2044768 for files needed to replicate