Eager Loading With Authlogic

August 23, 2012

I've used authlogic for authentication and session management on a number of projects. For one application, I wanted to eager-load an association at the time of a successful sign-in. I thought it'd be helpful to demonstrate the code here, since it took some digging through the documentation and other examples to figure out how to accomplish this.

Basically you want to create a new session within a with_scope block, and pass a find_options hash with whatever options you need. Here's the create action in the UserSessions controller:

class UserSessionsController < ApplicationController

def create
UserSession.with_scope(:find_options => {:include => :photos}) do
@user_session = UserSession.new(params[:user_session])
end
if @user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default account_url
else
render :action => :new
end
end
end

See Also

authlogic documentation