Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eager load associations with the current_user?

Tags:

I'm using Devise for authentication in my Rails app. I'd like to eager load some of a users associated models in some of my controllers. Something like this:

class TeamsController < ApplicationController

  def show
    @team = Team.includes(:members).find params[:id]
    current_user.includes(:saved_listings)

    # normal controller stuff
  end
end

How can I achieve this?

like image 794
David Tuite Avatar asked Aug 01 '11 18:08

David Tuite


2 Answers

I ran into the same issue and although everyone keeps saying there's no need to do this, I found that there is, just like you. So this works for me:

# in application_controller.rb:
def current_user
  @current_user ||= super && User.includes(:saved_listings).find(@current_user.id)
end

Note that this will load the associations in all controllers. For my use case, that's exactly what I need. If you really want it only in some controllers, you'll have to tweak this some more.

This will also call User.find twice, but with query caching that shouldn't be a problem, and since it prevents a number of additional DB hits, it still is a performance gain.

like image 132
Thilo Avatar answered Oct 19 '22 21:10

Thilo


Override serialize_from_session in your User model.

class User
  devise :database_authenticatable

  def self.serialize_from_session key, salt
    record = where(id: key).eager_load(:saved_listings, roles: :accounts).first
    record if record && record.authenticatable_salt == salt
  end
end

This will however, eager load on all requests.

like image 28
Vikrant Chaudhary Avatar answered Oct 19 '22 21:10

Vikrant Chaudhary