Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

ruby on rails - Can't troubleshoot undefined method "klass" for nil:NilClass; checked all my associations

My models look like this:

class ContractShipment < 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 < ApplicationRecord
  belongs_to :contract_shipment, optional: true
  has_many :liquor_lots
end

class LiquorLot < ApplicationRecord
  belongs_to :shipment_lot, optional: true
end

When I try to get run the following query, I get the "no method 'klass' for nil:NilClass" error.

LiquorLot.joins(shipment_lot: :contract_shipment)
         .where(tank_batch_id: 1, contract_shipments: {id: 1})
         .sum("liquor_lots.package_weight_kg * liquor_lots.package_count")

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 (shipment_lot(s): contract_shipment(s)) and neither of these options work.

Any idea what I'm missing?

Edit: the SQL query I'm trying to generate is:

SELECT SUM(liquor_lots.package_weight_kg * liquor_lots.package_count) 
FROM "liquor_lots" 
INNER JOIN "shipment_lots" ON "shipment_lots"."id" = "liquor_lots"."shipment_lot_id" 
INNER JOIN "contract_shipments" ON "contract_shipments"."id" = "shipment_lots"."contract_shipment_id" 
WHERE "liquor_lots"."tank_batch_id" = 1 AND "contract_shipments"."id" = 1

And this returns the value I'm expecting. Just want to avoid writing explicit SQL.

question from:https://stackoverflow.com/questions/65834969/cant-troubleshoot-undefined-method-klass-for-nilnilclass-checked-all-my-ass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...