How to eager load associations with the current_user?

前端 未结 4 754
暖寄归人
暖寄归人 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 06:13

    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.

提交回复
热议问题