title: Can't troubleshoot undefined method "klass" for nil:NilClass; checked all my associations
body: <p>My models look like this:</p>
  <pre><code>class ContractShipment &lt; ApplicationRecord
    has_many :shipment_lots, dependent: :restrict_with_exception
    has_many :liquor_lots, through: :shipment_lots
    accepts_nested_attributes_for :shipment_lots
  end
  
  class ShipmentLot &lt; ApplicationRecord
    belongs_to :contract_shipment, optional: true
    has_many :liquor_lots
  end
  
  class LiquorLot &lt; ApplicationRecord
    belongs_to :shipment_lot, optional: true
  end
  </code></pre>
  <p>When I try to get run the following query, I get the &quot;no method 'klass' for nil:NilClass&quot; error.</p>
  <pre><code>LiquorLot.joins(shipment_lot: :contract_shipment)
           .where(tank_batch_id: 1, contract_shipments: {id: 1})
           .sum(&quot;liquor_lots.package_weight_kg * liquor_lots.package_count&quot;)
  </code></pre>
  <p>I've looked, and re-looked at my associations and I can't seem to understand what I'm missing.  I've also tried making both of my joins plural (<code>shipment_lot(s): contract_shipment(s)</code>) and neither of these options work.</p>
  <p>Any idea what I'm missing?</p>
  <p>Edit:  the SQL query I'm trying to generate is:</p>
  <pre><code>SELECT SUM(liquor_lots.package_weight_kg * liquor_lots.package_count) 
  FROM &quot;liquor_lots&quot; 
  INNER JOIN &quot;shipment_lots&quot; ON &quot;shipment_lots&quot;.&quot;id&quot; = &quot;liquor_lots&quot;.&quot;shipment_lot_id&quot; 
  INNER JOIN &quot;contract_shipments&quot; ON &quot;contract_shipments&quot;.&quot;id&quot; = &quot;shipment_lots&quot;.&quot;contract_shipment_id&quot; 
  WHERE &quot;liquor_lots&quot;.&quot;tank_batch_id&quot; = 1 AND &quot;contract_shipments&quot;.&quot;id&quot; = 1
  </code></pre>
  <p>And this returns the value I'm expecting.  Just want to avoid writing explicit SQL.</p>