我知道之前已被问过,但我无法弄明白该怎么做。我正在努力加载对问题和答案的影响,但只有当前用户,将其视为检查用户是否已投票选择该项目....事件是基本项目。我最好不要加入,这样做。我的模型看起来像:
Event has many Questions
Question has many Answers
Event has many influences
Question has many influences
Answer has many influences
我尝试的是:
event.questions.includes(:answers, :influences)
但这会受到所有影响,而不仅仅是current_users。我也试过确定这些影响范围,但这似乎不起作用..我真的很难尝试定义'users_influences'has_many关联,我可以使用它而不是影响..
我想加载用户的影响,以便以热切的方式提供,问题和答案..澄清这种影响表有点像一个项目,将用户连接到这些其他各种实体..这可能没有连接吗?
答案 0 :(得分:2)
Monkey ActiveRecord::Base
configuration\initializers\monkey_patches.rb
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
在before_filter
中添加application_controller.rb
,以便在请求上下文中设置当前用户。
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