Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I thought this would get me what I needed, but it doesn't. Calling <code>feature.assets</code> (with <code>feature</code> as an item returned in my query) does another query to look for all <code>assets</code> related to that <code>feature</code>.</p> <pre><code>Feature.joins("LEFT OUTER JOIN assets on assets.feature_id = feature.id AND asset.issue_date = #{Date.tomorrow}") </code></pre> <p><strong>So here's what does work. Seems a little cleaner, too.</strong> My <code>Feature</code> model already has a <code>has_many :assets</code> set on it. I've set up <em>another</em> association with <code>has_many :tomorrows_assets</code> that points to <code>Assets</code>, but with a condition on it. Then, when I ask for <code>Feature.all</code> or <code>Feature.name_of_scope</code>, I can specify <code>.includes(:tomorrows_assets)</code>. Winner winner, chicken dinner.</p> <pre><code>has_many :tomorrows_assets, :class_name =&gt; "Asset", :readonly =&gt; true, :conditions =&gt; "issue_date = '#{Date.tomorrow.to_s}'" </code></pre> <p>I can successfully query <code>Features</code> and get just what I need included with it, only if it matches the specified criteria (and I've set <code>:readonly</code> because I know I'll never want to edit <code>Assets</code> like this). Here's an IRB session that shows the magic.</p> <pre><code>features = Feature.includes(:tomorrows_assets) feature1 = features.find_all{ |f| f.name == 'This Feature Has Assets' }.first feature1.tomorrows_assets =&gt; [#&lt;Asset id:1&gt;, #&lt;Asset id:2&gt;] feature2 = features.find_all{ |f| f.name == 'This One Does Not' }.first feature2.tomorrows_assets =&gt; [] </code></pre> <p>And all in only <em>two</em> SQL queries.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload