title: Rails as_json includes with conditions
body: <p>I have problems to restrict an as_json include by a dynamic attribute:</p>
  
  <pre><code>@pirates_ships = @current_account.pirates.as_json(:include =&gt; {:ships =&gt; {:only =&gt; [:id, :name]}}, :only =&gt; [:id, :last_name])
  </code></pre>
  
  <p>This for sure gives me all pirates with or without their ships.</p>
  
  <p>But I also need to <strong>restrict the ships by e.g. ships.ocean_id</strong></p>
  
  <p>I tried resolving it by includes with conditions:</p>
  
  <pre><code>pirates.includes(:ships).where("ships.ocean_id = ?", @ocean.id).as_json(...)
  </code></pre>
  
  <p>The restriction works, but now all pirates without a ship are lost.</p>
  
  <p>Also no luck with my own JOIN Syntax.</p>
  
  <p>Any ideas?
  Ahoy</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>My solution so far is to manually eager load. This way I can have my dynamic conditions:</p>
  
  <pre><code>@pirates = @current_account.pirates
  @ships = @current_account.ships.where({:pirate_id.in =&gt; @pirates, :ocean_id =&gt; @ocean.id})
  
  render :json =&gt; { :pirates =&gt; @pirates.as_json(...), :ships =&gt; @ships.as_json(...) }
  </code></pre>
  
  <p>My Ajax callback can now iterate over :pirates and add for each pirate his ships if any.
  (I use a JS template engine clientside to generate the view from the JSON response)</p>
  
  <p>Not very elegant, but performance is important in my case.</p>
  
  <p>I'am still open for better ideas.
  I tried dynamic has_many :ships, :conditions => ... 
  but that's a bit fiddly.</p>