ruby on rails - How to sum fields after group_by -
i need group records date, sum 1 field each of days.
this code i'm trying refactor:
<% @startdate.upto(@enddate) |date| %> <% visitors = @links.where("created_at >= ? , created_at < ?", date, date+1).order("created_at asc").select("id, visit_count") %> <%= datevisitors.sum("visit_count") || 0 %> <% end %>
i've started with:
<% visitors = @links.select("visit_count, created_at").group_by{|l| l.created_at.day} %> <% @startdate.upto(@enddate) |date| %> <%= visitors[date] ...? <% end %>
when group_by something, receive array of day , element. if group day, you'll have day , elements part of array:
<% @links.group_by{|l| l.created_at.day}.each |day, links| %> <p><%= day %>: <%= links.sum(&:visit_count) %></p> <% end %>
edit --
ok, in case code looks close:
<% visitors = @links.select("visit_count, created_at").group_by{|l| l.created_at.day} %> <% @startdate.upto(@enddate) |date| %> <% if visitors[date] %> <%= visitors[date].sum(&:visit_count) %> <% else %> 0 <% end %> <% end %>
it's better move helper (or presenter)
def daily_visits(links, from, to) links_by_day = links.select("visit_count, created_at").group_by{|l| l.created_at.day} range = from.upto(to).to_a range.inject({}) |date, hash| hash[date] = links_by_day.fetch(date, 0) end end
then, in view:
<% daily_visits(@links, @startdate, @enddate).each |day, count| %> <%= day %>: <%= count %> <% end %>
Comments
Post a Comment