Rails select()和count()看起来玩起来不太好

问题描述 投票:8回答:3

[我注意到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

但是现在问题开始了。当我在[[both 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

为什么countsize(在这种情况下为count的别名)引发异常,并且仅当我选择

多个]属性时]

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

我注意到Rails(4.1)ActiveRecord有点奇怪,其中选择和计数有时会混合在一起:User.all.count => 103 User.all.size => 103 User.all.length => 103到目前为止,这么好。我...

sql ruby-on-rails activerecord ruby-on-rails-4 ruby-on-rails-4.1
3个回答
10
投票
这是Rails 4.1中的错误。参见https://github.com/rails/rails/issues/13648

1
投票
当您使用select并且一个参数有多个列时,您需要将其以这种格式放入字符串中:

0
投票
感谢@camomileCase给您的提示。
© www.soinside.com 2019 - 2024. All rights reserved.