根据我编写的代码,我试图按日期进行安排
@period = Date.new(2019,3,1)..Date.new(2019,3,31)
@deals = Deal.includes(:staff).where(shop_id:1, created_at:@period).group_by{|t| t.staff}
我在函数computed_deals
中创建了一个每天要出售的每个员工项目的总和
def computed_deals(deals, period ,shop_id)
#step 1 create empty container and initialize the value
data = {}
staff_id_container = {
total:{item1: 0, item2: 0, item3: 0}
}
Staff.where(shop_id: shop_id).select(:id).each do |staff|
staff_id_container[staff.id] = {item1:0, item2:0, item3:0}
end
period.each do |date|
data[date] = staff_id_container.dup
end
#step2 fill it up by true value
deals.each do |staff, deals_by_staff|
deals_by_staff.group_by{|t| t.created_at.to_date}.each do |date, selected_deals|
data[date][staff.id] = {
item1: select_deals.select{|deal| deal.item == "item1"}.count
item2: select_deals.select{|deal| deal.item == "item2"}.count
item3: select_deals.select{|deal| deal.item == "item3"}.count
}
end
end
#step3 make sum from each staff for each day
period.map do |date|
sum_item1 = sum_item2 = sum_item3 = 0
puts "top"
puts sum_item1
deals.each do |staff, deals_by_staff|
sum_item1 = data[date][staff.id][:item1]+sum_item1
sum_item2 = data[date][staff.id][:item2]+sum_item2
sum_item3 = data[date][staff.id][:item3]+sum_item3
end
data[date][:total][:item1] = sum_item1.dup
data[date][:total][:item2] = sum_item2.dup
data[date][:total][:item3] = sum_item3.dup
puts "bottom"
puts sum_item1
end
end
但是在步骤3中,total
的所有值都是从最后一天开始复制的。
我认为问题在于每次执行迭代时都更改了变量,并且给出的值也同时更改了。
@data = computed_deals(@period, @deals, 1)
puts @data["2019-03-01".to_date][:total] == @data["2019-03-02".to_date][:total] #true
我该如何解决这个问题?