Rails select () and count () don't seem good

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.

+6
source share
2 answers

This is a bug in Rails 4.1. See https://github.com/rails/rails/issues/13648

+8
source

When you use select and you have several columns for the argument, you need to put it in a row in this format:

 User.select("id, email") 

In other words, the list of columns should only be transmitted in a clean row in the format

+1
source

All Articles