I noticed something strange with Rails (4.1) ActiveRecord, where select and count sometimes mix poorly:
User.all.count => 103 User.all.size => 103 User.all.length => 103
So far so good. I can choose id :
User.select(:id).all.count => 103 User.select(:id).all.size => 103 User.select(:id).all.length => 103
Still good. I can also select by email :
User.select(:email).all.count => 103 User.select(:email).all.size => 103 User.select(:email).all.length => 103
But now the problems begin. When I select both id and email :
User.select(:id, :email).all.count (0.4ms) SELECT COUNT(id, email) FROM `users` Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` User.select(:id, :email).all.size (0.4ms) SELECT COUNT(id, email) FROM `users` Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` ActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email) FROM `users`' at line 1: SELECT COUNT(id, email) FROM `users` User.select(:id, :email).all.length => 103
Why is it count and size (which in this case use aliases for count ) throw an exception and only when I select more than one attribute?
Is there any explanation for this? I find this completely unexpected.
source share