Reputation: 1252
I have a simple rails query like
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. This is a fine behavior. But in my case rails ends up executing 2 queries because I call a.count
before operating on a
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.
Upvotes: 1
Views: 49
Reputation: 12361
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.
a = A.where(type: 'user').entries
if a.count > 1
#Log Information
end
return a
Upvotes: 4