Search code examples
ruby-on-railshstore

Rails sum query with hstore


I have got a table with an hstore column. What I need to do is sumarize all of the entries of a specific hstore key.

one Stat record looks like this:

 id: 2041,
 tenant_name: "isabela",
 totals:
 {"value1"=>"31",
 "value2"=>"21",
 "value3"=>"38",
 "value4"=>"28",
 "value5"=>"0"},
 created_at: Tue, 05 May 2015 23:31:01 UTC +00:00,
 updated_at: Tue, 05 May 2015 23:31:01 UTC +00:00>,

With totals being the hstore column. What i would like is to find the sum of every records value1 for a specific day. so far i got:

string = [];
dates.each do |date|
  count = Stat.where(created_at: DateTime.parse(date).midnight..DateTime.parse(date).midnight + 1.day))
  string.push(count)
end
//(dates = an array of dates)

Does anyone have a good idea how to do this?

update got it to work with:

.sum("(totals->'value1')::integer")

Solution

  • You should do :

    sums = dates.map do |date|
      Stat.where(created_at: DateTime.parse(date).midnight..DateTime.parse(date).midnight + 1.day))
          .sum("totals->'value1'::integer")
    end
    

    sums now holds the summation of value1 of all records/per day.