rails/arel — Issue #97: Applying conditions to object to be eager loaded via includes
Author: derekprior
Created: 2012-01-25 18:52:17+00:00
State: open

As far as I can tell, it's currently not possible to apply conditions to models that are eager loaded using the `includes` method. For instance, given the following models:

```ruby
class Shift < ActiveRecord::Base
has_many :schedules
end

class Schedule < ActiveRecord::Base
belongs_to :shift
end
```

And a desire to select all shifts, eager loading any schedules that occur on a given date, one would think to do something like:

```ruby
Shift.includes(:schedules).where(:schedules => { :occurs_on => Date.today })
```

Unfortunately, this will cause all shifts without schedules for the given day to be removed from the results as the filtering occurs in the `where` clause.

Shouldn't there be a way to apply conditions on the associated objects to be eager loaded? The best I've been able to come up with is:

```ruby
Shift.includes(:schedules).where("schedules.occurs_on is null OR schedules.occurs_on = '#{Date.today}'")
```

This is ugly and non obvious. Ideally, I'd be able to say:

```ruby
Shift.includes(:schedules => {:occurs_on => Date.today}}
```

But when doing this, ActiveRecord errors saying that :occurs_on is not a relation. This syntax is already used for nesting includes.

Any ideas on how to proceed?