title: Why are my thread variables intermittent in Rails?
body: <p>I have the following in my application controller:</p>
  
  <pre><code>before_filter :set_current_subdomain
  
    protected
      def set_current_subdomain
        Thread.current[:current_subdomain] = current_subdomain
        @account = Account.find_by_subdomain(current_subdomain)
      end
  
      def current_subdomain
        request.subdomain
      end
  </code></pre>
  
  <p>and then the following in some of my models:</p>
  
  <pre><code>default_scope :conditions =&gt; { :account_id =&gt; (Thread.current[:account].id unless Thread.current[:account].nil?) }  
  </code></pre>
  
  <p>Now, this works - some of the time. I for instance load up an index method and get back a list of records with the scope applied, but also sometimes get an empty list as Thread.current[:account_id] is coming out as nil, even though queries earlier in the request are working using the same value.</p>
  
  <p>Question is, why is this not working, and is there a better way to set a variable that's global to the current request?</p>