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:
c
I wanted to add what I think is a better solution. As noted in comments, existing solutions may hit your DB twice with the find
request. Instead, we can use ActiveRecord::Associations::Preloader
to leverage Rails' work around loading associations:
def current_user
@current_user ||= super.tap do |user|
::ActiveRecord::Associations::Preloader.new.preload(user, :saved_listings)
end
end
This will re-use the existing model in memory instead of joining and querying the entire table again.