Skip to content
Advertisement

Rails select() and count() don’t seem to play nice

I’ve noticed something odd with Rails (4.1) ActiveRecord, where select and count sometimes mix badly:

User.all.count
 => 103
User.all.size
 => 103
User.all.length
 => 103

So far, so good. I can select on 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 on email:

User.select(:email).all.count
 => 103
User.select(:email).all.size
 => 103
User.select(:email).all.length
 => 103

But now problems begin. When I select on 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 that count and size (which in this case aliases to count) are throwing an exception, and only when I select more than one attribute?

Is there an explanation for this? I find this quite unexpected.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement