How to iterate over ActiveRecord relation through a has_many association

39 Views Asked by At

So i've got certain IceCream in which i'd like to get the sales amount in Ontario of low fat ice cream and non expired, say.

IceCream has_many ontario_sales_receipts:

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

But this results in:

undefined method `ontario_sales_receipts' for #<IceCream::ActiveRecord_Relation:0x0055de80e3ffa8>

How do I make available a has_many association from an ActiveRecord relation?

I could originally query OntarioSaleRecept, but I don't know how to query them based on their has_one association with specific IceCream

included_ontario_sales_receipts = OntarioSalesReceipt.where( their associated IceCream is lowfat and non expired ... )
1

There are 1 best solutions below

0
Kinley Wangchuk On
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

how about this?