所以我有某些冰淇淋,我想获得安大略省低脂冰淇淋和未过期冰淇淋的销售额。
冰淇淋有很多安大略省销售收据:
included_ice_cream = IceCream.produced_this_or_previous_month.where(low_fat: true, expired: false)
final_amount = included_ice_cream.ontario_sales_receipts.pluck(:number_of_buckets).sum * BUCKET_PRICE
但这会导致:
undefined method `ontario_sales_receipts' for #<IceCream::ActiveRecord_Relation:0x0055de80e3ffa8>
如何从 ActiveRecord 关系中获取 has_many 关联?
我最初可以查询 OntarioSaleRecept,但我不知道如何根据它们与特定 IceCream 的 has_one 关联来查询它们
included_ontario_sales_receipts = OntarioSalesReceipt.where( their associated IceCream is lowfat and non expired ... )
included_ice_cream = IceCream.produced_this_or_previous_month.where(
low_fat: true,
expired: false
)
total_amount = final_amount(included_ice_cream)
def final_amount(included_ice_cream)
included_ice_cream.map do |ice_cream|
ice_cream.ontario_sales_receipts.pluck(:number_of_buckets).sum *
BUCKET_PRICE
end.sum
end
这个怎么样?