8

我注意到 Rails (4.1) ActiveRecord 有一些奇怪的地方selectcount有时混合得很糟糕:

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

到目前为止,一切都很好。我可以选择id

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

还好。我也可以选择email

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

但现在问题开始了。当我同时选择 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

为什么countand size(在这种情况下是 的别名count)会引发异常,并且仅当我选择多个属性时?

对此有解释吗?我觉得这很出乎意料。

4

3 回答 3

10

这是 Rails 4.1 中的一个错误。见https://github.com/rails/rails/issues/13648

于 2014-05-21T01:20:06.173 回答
0

当你使用select一个参数并且你有多个列时,你需要将它放在一个字符串中,格式如下:

User.select("id, email")

换句话说,列列表只能以纯字符串格式传递

于 2014-04-29T11:38:05.977 回答
0

感谢@camomileCase 的提示。

在我的情况下,我通过添加选项解决了它count:all有时count如果需要添加一个附加选项。这种方式非常适合我:

@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
于 2019-11-28T06:03:40.100 回答