I'm trying to get from the statistics table the last record from the last day of each customer. I want to select the customer with the most sold items from the last day.
The stats are generated every hour so there are multiple statistics from the customer, but I need just the last one.
I tried several commands I just receive errors.
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.order(created_at: :desc)
or
Statistic.where("created_at < ?",1.day.ago).select(:customer_id).distinct.last
Is the best solution with pluck? Or should I create 2 selects? I have no idea where I should place 'sold_items'.
this could be also a solution, but I'm not sure.
Customer.all.each do |customer|
stats = customer.statistics.where("created_at < ?",Date.today).last
count = stats.sold_items if stats.sold_items > count
best = customer if count = stats.sold_items
end
The Models: customer has_many :statistics - Statistic belongs_to :customer