【问题标题】:Rails select() and count() don't seem to play niceRails select() 和 count() 似乎不太好用
【发布时间】:2014-04-29 08:01:08
【问题描述】:

我注意到 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 的别名)会抛出异常,并且只有当我选择多个 属性时?

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

【问题讨论】:

  • 你试过没有.all - User.select(:id, :email).size 吗?
  • @RichPeck 恐怕User.select(:id, :email).size 会抛出同样的异常。

标签: sql ruby-on-rails activerecord ruby-on-rails-4 ruby-on-rails-4.1


【解决方案1】:

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

【讨论】:

  • 如果你受到这个错误的影响,这个问题谈到需要通过 :all 来计数。 IE。 User.select(:id, :email).count(:all)
  • @camomileCase 很棒的提示。
【解决方案2】:

当您使用select 并且您有多个列用于参数时,您需要将其放入字符串中,格式如下:

User.select("id, email")

换句话说,列列表只能以pure string格式传递

【讨论】:

  • 虽然生成的 SQL 略有不同——使用符号生成SELECT 'users'.'id', 'users'.'email' FROM 'users',使用字符串生成SELECT id, email FROM 'users'——运行User.select("id, email").size时仍然出现异常。
【解决方案3】:

感谢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多