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

When Active Record has already loaded a unique association .size returns the wrong number. #5453

Conversation

JonRowe
Copy link
Contributor

@JonRowe JonRowe commented Mar 15, 2012

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

@jeremyf
Copy link
Contributor

jeremyf commented May 7, 2012

The tests all pass for this bug fix. @tenderlove @jonleighton

tenderlove added a commit that referenced this pull request May 17, 2012
…any_when_already_loaded

When Active Record has already loaded a unique association `.size` returns the wrong number.
@tenderlove tenderlove merged commit 0821295 into rails:master May 17, 2012
@tenderlove
Copy link
Member

@jeremyf thanks for the confirmation! ❤️

@JonRowe
Copy link
Contributor Author

JonRowe commented May 17, 2012

Thanks @tenderlove :)

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

Successfully merging this pull request may close these issues.

has_many through with uniq and preloading ignores uniq when calling collection size
3 participants