Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Active Record select parent and child as one result

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.

like image 554
Oranges13 Avatar asked Jul 24 '12 19:07

Oranges13


1 Answers

If you want to specify SQL in detail, you can always try find method passing :include, :joins, :where etc. includes or joins does same thing down the line when you try to access to data but behaviour of activerecord is different. For example, following 3 ways set up object array but they are different.

[1]

alerts = Alert.joins(:polling)

[2]

alerts = Alert.includes(:polling)

[3]

alerts = Alert.find(:all, :includes => :polling, :joins => :polling)

when you do

alerts.each do |alert|
  alert.pollings.each do |polling|
    p polling
  end
end

you can see how activerecord tries to get data from DB or cache. The [3] way, I believe, throws only one query when others throw multiple queries.

like image 74
mask8 Avatar answered Nov 11 '22 11:11

mask8