This is a bug in Rails 4.1. See https://github.com/rails/rails/issues/13648
Rails select() and count() don't seem to play nice
-
11-07-2023 - |
Question
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.
Solution
OTHER TIPS
When you use select
and you have more than one columns for an argument, you need to put it in a string, in this format:
User.select("id, email")
In other words, the list of columns should only be passed in pure string format
Thanks @camomileCase for your tip.
In my case I've resolved it by adding count
with :all
option, and sometimes adding an additional count
if needed. This way works perfect for me:
@grid = myscope.select(:thickness, :width, :length, "SUM(quantity_available) as quantity_available").group(:thickness, :width, :length)
@grid.assets.limit(nil).count(:all)
@grid.assets.limit(nil).count(:all).count