Slow ActiveRecord

Hi everyone. I’ve used AR for years for fairly big queries and it’s the
first time I see such an impact in my performance, so I guess I’m doing
something wrong or missing something very obvious.
The query on PostgreSQL takes 22ms to complete, but the page is taking
seconds to render. My guess is that AR is taking a lot of time to take
data and build objects out of it. Of course this is not my production
machine, but my mac. Still, I would like to understand what’s the
here and fix it ASAP, even 8 sec to render the page on production would
quite a disaster…

I’ve tried to ask on SO, but that was the wrong question: I was
the output of EXPLAIN ANALYZE.

This is my query:

def self.with_facilities
includes( :provinces => { :municipalities => :facilities }
).select( “, states.slug,,
).where( ‘ IS NOT NULL’ )

As you can see it’s a rather big join, but the biggest table has 14k
records, so no big deal.
The point of this query, is finding all states and provinces with at
1 facility in the DB.
The select is completely ignored, apparently because eager loading is
applied very late in the query execution.
The problem, I think, is that Rails instances a ton of objects from the
data, even though I only need a bunch of fields to populate a menu…

How can I fix this? Has someone ever experienced anything like this? I
might even try to avoind eager loading completely, but I’m not entirely
sure how to do that.

Any help is appreciated, it’s already a few days I’m trying to solve
this… I can provide every information that is needed about the schema,
indexes, and whatever else is needed, I just thought it wasn’t
the query itself is obviously performing quite well…


On Mon, Aug 13, 2012 at 5:16 AM, ngw [email protected] wrote:

The query on PostgreSQL takes 22ms to complete,
but the page is taking 21 seconds to render.

Is that from submission to completion, or specifically the rendering,
after the controller has gathered all the data, done any processing
needed, and passed it along? Can you show us the view code?


Dave A., Available Secret-Cleared Ruby/Rails Freelancer
see,, and for more