Note that there are some explanatory texts on larger screens.

plurals
  1. POEagerloading with scoping in rails3
    primarykey
    data
    text
    <p>I have been trying to eager load associations based on some scope in my rails3 app, but could not find any solution.</p> <p>My app has following models:</p> <pre><code>class Project has_many :entries has_many :to_dos class ToDo has_may :entries has_many :tasks belongs_to :project class Task has_many :entries belongs_to :to_do class Entry belongs_to :project belongs_to :to_do belongs_to :task # options format: {:from_date=&gt;(Date.today-1.week), :to_date=&gt;(Date.today+1.week), :user_id=&gt;60} scope :filtered_list, lambda { |options| condition = options[:user_id].nil? ? "true" : "user_id = #{options[:user_id]}" condition += options[:from_date].nil? ? "" : " AND entry_date &gt;= '#{options[:from_date]}'" condition += options[:to_date].nil? ? "" : " AND entry_date &lt;= '#{options[:to_date]}'" where(condition) } </code></pre> <p>And in projects#index i have following code to get all projects of an user:</p> <pre><code>@projects = current_user.projects.includes(:entries, :to_dos =&gt;[:entries, :tasks =&gt; :entries]) </code></pre> <p>It fetches all projects of the user, along with eager loading the associations. So when i perform following loop to get all the entries within the project, no new query gets fired.</p> <pre><code>def all_entries(options) entries = self.entries self.to_dos.each do |d| entries += d.entries d.tasks.each do |t| entries += t.entries end end end </code></pre> <p>As this eager loading fetches all entries, it is way too much data than what I actually needed. So I tried to apply some conditions to the entries eager loaded, but could not find any solution. I was looking for something like:</p> <pre><code>@projects = current_user.projects.includes(:entries.filtered_list(options), :to_dos =&gt;[:entries.filtered_list(options), :tasks =&gt; :entries.filtered_list(options)]) </code></pre> <p>So that only the entries satisfying some conditions get loaded.</p> <p>Can't we use scoping with eager loading? Please help me out use eagerloading alongside scoping.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
 

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