title: ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column for `where` query when using includes
body: <p>I have the following associations:</p>
  
  <p>mobile_application.rb</p>
  
  <pre><code>has_many :events
  </code></pre>
  
  <p>event.rb</p>
  
  <pre><code>belongs_to :mobile_application
  </code></pre>
  
  <p>The following runs properly:</p>
  
  <pre><code>MobileApplication.includes(:events)
  #=&gt; MobileApplication Load (1.6ms)  SELECT `mobile_applications`.* FROM `mobile_applications`  ORDER BY created_at desc
  #   Event Load (1.3ms)  SELECT `events`.* FROM `events` WHERE `events`.`mobile_application_id` IN (746, 745, 744, ....
  </code></pre>
  
  <p>but when I tried with the following,</p>
  
  <pre><code>MobileApplication.includes(:events).where("events.expiry_date &gt;= ?", Time.zone.now)
  </code></pre>
  
  <p>it throws an error:</p>
  
  <pre><code>MobileApplication Load (1.2ms)  SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date &gt;= '2019-02-18 07:34:40.738517')  ORDER BY created_at desc
  Mysql2::Error: Unknown column 'events.expiry_date' in 'where clause': SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date &gt;= '2019-02-18 07:34:40.738517')  ORDER BY created_at desc
  ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'events.expiry_date' in 'where clause': SELECT `mobile_applications`.* FROM `mobile_applications` WHERE (events.expiry_date &gt;= '2019-02-18 07:34:40.738517')  ORDER BY created_at desc
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>Please suggest how I can filter it. Using <code>references</code> also throws the following error &amp; also got same with answer provided by Marek Lipka,</p>
  
  <pre><code>ActiveRecord::StatementInvalid: Mysql2::Error: Column 'created_at' in 
  order clause is ambiguous: SELECT `mobile_applications`.`id` AS t0_r0, 
  `mobile_applications`.`name` AS t0_r1, ...
  </code></pre>
  
  <p>I guess it is due to column ambiguity created by <code>default_scope</code> present in model to order it by <code>created_at</code> which is present in both associated tables.</p>