Rails Active Record select parent and child as one result

Viewed 3124

I have a parent / child relationship in my application

class Polling
 has_many :alerts, :dependent => :destroy

class Alert
 belongs_to :polling

On my index page for the alerts, I need to show some data from each parent, and this results in two queries

Alert Load (6.1ms)  SELECT * FROM (SELECT * FROM "ALERTS" INNER JOIN "POLLINGS" ON "POLLINGS"."ID" = "ALERTS"."POLLING_ID" ORDER BY "ALERTS"."ID" DESC) WHERE ROWNUM <= 1
Polling Load (1.8ms)  SELECT "POLLINGS".* FROM "POLLINGS" WHERE "POLLINGS"."ID" = 10113 AND ROWNUM <= 1

Obviously, this makes the page loading time quite horrendous as it has to loop through each one and pull the parent object as well.

I have tried a few things, such as

> Alert.joins(:polling).where(...)
> Alert.includes(:polling).where(...)
> Alert.joins(:polling).select('*').where(...)

And each time I get two distinct queries when I visit my index page. One for each Alert, and then another to get its parent data. How can I do this on one line so that when I pull the alerts I also get their associated parent data? There doesn't seem to be a way to go about it from the other end because if I do a Pollings.where(...) it doesn't grab the children as a group.

1 Answers
Related