Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As far as I know, scopes cannot be applied to included associations like this. However, you can specify conditions that should only be applied to the eager loading queries. So with a bit of refactoring, you could have a method that only created the conditions you currently define in your scope:</p> <pre><code>def self.filter_by(options) condition = options[:user_id].nil? ? "true" : "entries.user_id = #{options[:user_id]}" condition += options[:from_date].nil? ? "" : " AND entries.entry_date &gt;= '#{options[:from_date]}'" condition += options[:to_date].nil? ? "" : " AND entries.entry_date &lt;= '#{options[:to_date]}' condition end </code></pre> <p>or a bit more rubyesque:</p> <pre><code>def self.filter_by(options) conditions = [] conditions &lt;&lt; "entries.user_id = #{options[:user_id]}" unless options[:user_id].nil? conditions &lt;&lt; "entries.entry_date &gt;= '#{options[:from_date]}'" unless options[:from_date].nil? conditions &lt;&lt; "entries.entry_date &lt;= '#{options[:to_date]}'" unless options[:to_date].nil? conditions.join(" AND ") end </code></pre> <p>and then chain that method to your eager loading:</p> <pre><code>@projects = current_user.projects.includes(:entries, :to_dos =&gt;[:entries, :tasks =&gt; :entries].where(Entry.filter_by(options)) </code></pre> <p>and also reuse it in your scope if you need it independently:</p> <pre><code>scope :filtered_list, lambda { |options| where(Entry.filter_by(options)) } </code></pre> <p>Disclaimer: None of this is tested with your actual model definitions, but it works fine with some pretty equivalent ones that I had lying around.</p> <p>Also note that if the filter options ultimately come from the client side, your condition is vulnerable to SQL injection.</p> <p>Behind the scenes, Rails uses a JOIN to load the relevant data, so that is something to be aware of. It might be a good thing (a few less queries) or a bad thing (if your indexing is suboptimal). That's probably why the <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow">guide</a> has this to say:</p> <blockquote> <p>Even though Active Record lets you specify conditions on the eager loaded associations just like joins, the recommended way is to use joins instead.</p> </blockquote>
 

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