Stan K.
Stan K.

Reputation: 487

Eager loadings for single object?

I have a controller that find 1 record (its uniq)

class CollectionsController < ApplicationController
  def show
    @collection = Collection.find_by_active(true)
  end
end

This '@collection' have many :items, which has many :photos

So, in view it look like this:

- @collection.items.each do |item|
    = image_tag item.find_active_photo.image_url(:small)

And it will reproduce bunch of SQL queries, for example if item has 4 photos, it will be 6 queries:

Collection Load 
CollectionItem Load 
Photo Load (4 times)

How I can reduce count of this N+1 queries?

Upvotes: 0

Views: 182

Answers (3)

messanjah
messanjah

Reputation: 9288

For Rails 4

@collection = Collection.includes(items: :photos).find_by_active(true)

Upvotes: 0

Denis Yagofarov
Denis Yagofarov

Reputation: 61

There is an "includes" method of ActiveRecord. It allows to preload records.

Collection.find_by_active(true).includes(:items)

Not sure, if you can do something like includes(items: :photo), but give it a try.

Upvotes: 0

rderoldan1
rderoldan1

Reputation: 4088

use eager loading

@collection = Collection.find_by_active(true, {:include =>{:items => :photos})

Upvotes: 1

Related Questions