2
votes

I'm working on optimizing some queries in my rails app (postgres), on some queries where I'm loading up a bunch of Activerecord objects and checking for any? on them, I see queries like this in my log file

SELECT
    COUNT(count_column)     
FROM
    (SELECT
        1 AS count_column 
    FROM
        "questions" 
    WHERE
        "questions"."deleted_at" IS NULL 
        AND "questions"."place_id" = 1 
        AND "questions"."publish_state" = 'published' LIMIT 6) subquery_for_count  

I'm wondering why this is. I thought Rails would just do a count of items in memory instead of issuing a DB call to get this number?

Why would it pull everything out of the database just to count them and throw them away? - mu is too short
Ahh no ... it actually loads the records, but those happen when I do something like call any? or present? on the associations I just loaded. So for example, if I do something like ... q = Question.limit(5).all, then call q.any? ... then I'll see the query I just described up top - concept47
If you call any? on a relation object it goes to the database because that's what you asked it to do. The relation doesn't know what you have in memory, it only knows how to talk to the database. - mu is too short
.all doesn't return a relation object, but I see what you're saying (.find calls for example). Is there a way to avoid this db, will .size.zero? do what I want since size is supposed to use AR objects in memory if they're already loaded? - concept47
If you want to use the objects in memory then you'll probably have to ask them directly (i.e. store them in an array and talk to the array). - mu is too short