如何急切加载与current_user的关联?
我在我的Rails应用程序中使用Devise进行身份validation。 我想在我的一些控制器中急切加载一些用户关联的模型。 像这样的东西:
class TeamsController < ApplicationController def show @team = Team.includes(:members).find params[:id] current_user.includes(:saved_listings) # normal controller stuff end end
我怎样才能做到这一点?
我遇到了同样的问题,虽然每个人都说没有必要这样做,但我发现就像你一样。 所以这对我有用:
# in application_controller.rb: def current_user @current_user ||= super && User.includes(:saved_listings).find(@current_user.id) end
请注意,这将加载所有控制器中的关联。 对于我的用例,这正是我需要的。 如果你真的只想在某些控制器中使用它,你将不得不进一步调整它。
这也将调用User.find
两次,但是查询缓存不应该是一个问题,并且因为它可以防止大量额外的数据库命中,所以它仍然是性能提升。
在User
模型中覆盖serialize_from_session
。
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
但是,这将迫切需要加载所有请求。
为什么不在模型上使用default_scope呢?
像这样:
Class User < ActiveRecord::Base ... default_scope includes(:saved_listings) ... end