Rails Active Record selects 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 warning index page, I need to show some data from each parent, and this leads to 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 load time pretty awful, as it has to go through each of them and also extend the parent object.

I tried several things, for example

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

, , . , . , , , ? , , , Pollings.where(...), .

+5
1

SQL, find: include,: join,: where .. includes joins , , activerecord . , 3 , .

[1]

alerts = Alert.joins(:polling)

[2]

alerts = Alert.includes(:polling)

[3]

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

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

, activerecord . , [3] , .

+2

All Articles