Rails select()和count()似乎不太好玩

ist*_*ses 8 sql activerecord ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.1

我注意到Rails(4.1)ActiveRecord有些奇怪,在哪里select,count有时混合不好:

User.all.count
 => 103
User.all.size
 => 103
User.all.length
 => 103
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.我可以选择id:

User.select(:id).all.count
 => 103
User.select(:id).all.size
 => 103
User.select(:id).all.length
 => 103
Run Code Online (Sandbox Code Playgroud)

还好.我也可以选择email:

User.select(:email).all.count
 => 103
User.select(:email).all.size
 => 103
User.select(:email).all.length
 => 103
Run Code Online (Sandbox Code Playgroud)

但现在问题开始了.当我选择上 idemail:

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
Run Code Online (Sandbox Code Playgroud)

为什么它countsize(在这种情况下是别名count)抛出异常,并且只有当我选择多个属性时?

对此有解释吗?我觉得这很意外.

use*_*664 10

这是Rails 4.1中的一个错误.请参阅https://github.com/rails/rails/issues/13648

  • 如果你受到这个bug的影响,这个问题谈到需要通过:所有要计算.即`User.select(:id,:email).count(:all)` (6认同)