rails/rails — Issue #4677: ActiveRecord: Can't apply conditions on objects eager loaded via includes
Author: derekprior
Created: 2012-01-25 19:31:56+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 any 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.

Has this issue been discussed before? Is there an existing solution I'm not aware of or does anyone have any suggestions on how a patch would work to address this?