简体   繁体   English

Rails查询执行2个查询

[英]Rails query executes 2 queries

I have a simple rails query like 我有一个简单的Rails查询,例如

a = A.where(type: 'user')
if a.count > 1
  #Log Information
end
return a

Rails does lazy loading where it doesn't query the database unless some operation on the result set is executed. 除非对结果集执行某些操作,否则Rails会在不查询数据库的地方进行延迟加载。 This is a fine behavior. 这是很好的行为。 But in my case rails ends up executing 2 queries because I call a.count before operating on a 但是在我的情况下,rails最终执行了2个查询,因为我在操作a之前先调用a.count

SELECT COUNT(*) FROM `a` WHERE `a`.`type` = 'user';
SELECT  `a`.* FROM `a` WHERE `a`.`type` = 'user';

Is there any way I can ask rails to perform the query immediately so that only the second query is executed and the count is returned from the dataset. 有什么方法可以要求Rails立即执行查询,以便仅执行第二个查询,并从数据集中返回计数。

You can force the results into an array. 您可以将结果强制放入数组。 I think that to_a will work for that, but entries is a clearer way express that intention since its job is to iterate over the items in an Enumerable and return an array of the enumerated results. 我认为to_a可以解决这个问题,但是entries是表达此意图的一种更清晰的方法,因为它的工作是对Enumerable的项目进行迭代并返回枚举结果的数组。

a = A.where(type: 'user').entries
if a.count > 1
  #Log Information
end
return a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM