猴子在configuration\initializers\monkey_patches.rb 中修补ActiveRecord::Base
class ActiveRecord::Base
# Use thread local variables to store the context.
def self.current_user=user
Thread.current[:current_user]= user
end
def self.current_user
Thread.current[:current_user]
end
def current_user
ActiveRecord::Base.current_user
end
end
在application_controller.rb 中添加before_filter 以在请求上下文中设置当前用户。
class ApplicationController < ActionController::Base
before_filter :init_app_request
def init_app_request
ActiveRecord::Base.current_user = current_user # set the current user
end
end
现在修改Question 模型中的关联。添加一个名为 current_user_influences 的新关联,它将根据当前用户过滤影响。
class Question
has_many :influences,
# use single quotes for the `conditions` string to avoid interpolating
# the string during class loading.
has_many :current_user_influences, :class_name => "Influence",
:conditions => '#{current_user_check}'
def current_user_check
current_user ? "influences.user_id = #{current_user.id} " : ""
end
end
现在你可以预先加载current_user_influences:
questions =event.questions.includes(:answers, :current_user_influences)
# influences pertaining to the current user
questions.first.current_user_influences