【问题标题】:How to put conditions on an eager loading without Join?如何在没有加入的情况下为急切加载设置条件?
【发布时间】:2012-02-02 22:59:21
【问题描述】:

我知道以前有人问过,但我不知道该怎么做。我正在尝试加载对问题和答案的影响,但只有当前用户,将其视为检查用户是否为该项目投票......一个事件是基本项目。我想最好在没有连接的情况下这样做。我的模型看起来像:

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 关联,我可以使用它来代替影响..

我想加载用户的影响,以便他们能够以急切的加载方式提供问题和答案。澄清这个影响表有点像一个行项目,将用户连接到其他各种实体..这可能没有加入吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    猴子在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 
    

    【讨论】:

    • 哇,谢谢,多么棒的答案。你是这个社区的资产。谢谢。
    • @Inc1982 你能告诉我解决方案是否对你有用吗?我对解决方案进行了空中编码。如果当前解决方案有错误,我想更新答案。
    • @HarishShetty,只是想知道为什么你使用 Thread.current 而不是实例变量?有什么不同吗?
    • 另一种解决方案是在这些模型上使用带有 current_user 的默认范围。
    • @Chamnap,您可以使用静态变量或线程局部变量来存储当前用户。这样,当前用户可以访问控制器请求上下文中的任何对象。为当前用户使用线程局部变量可确保变量在多线程部署中不会被覆盖。(例如:JRuby/Rails4 等)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多