title: ActiveRecord to_json: conditionally include associations
body: <p>I'm trying to find a way to conditionally include associated models when I use .to_json on a model.</p>
  
  <p>In a simplified example, assume the following two models:</p>
  
  <pre><code>class Foo &lt; ActiveRecord::Base
    has_many :bars
  end
  
  class Bar &lt; ActiveRecord::Base
    belongs_to :foo
    attr_accessible :bar_type
  end 
  </code></pre>
  
  <p>I currently have:</p>
  
  <pre><code>f = Foo.find "3"
  j = f.to_json(:include =&gt; { :bars =&gt; {:some, :attributes}}
  </code></pre>
  
  <p>and this works. What I need to find a way to do is only include bar instances that have bar_type == 'what?'</p>
  
  <p>I'm hoping there's a way to conditionally pulling in the bar instances, or perhaps even use a scope to limit the bars that are included in the json output.</p>