How to eager load associations with the current_user?

前端 未结 4 819
暖寄归人
暖寄归人 2021-02-07 05:33

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         


        
4条回答
  •  没有蜡笔的小新
    2021-02-07 05:50

    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.

提交回复
热议问题