I have the following code that takes results, groups them by date and creates a customer count for that date, and then inserts it in to a Calculation
table:
customers.group_by { |c| Date.parse c.created.to_s }.map do |date, v|
value = v.map {|h1| 1}.sum
Calculation.find_or_initialize_by(
account_id: a.id,
metric: 'active_customers',
occurred_on: date
).update(
value: value
)
end
If there are hundreds of dates, it has to run find_or_initialize_by
...hundreds of times.
What I'd love to do is somehow avoid doing hundreds of "finds" and "creates" and somehow pull of just a couple of database calls.
The reason being that I'm hitting issues with number of database connections with so many finds/inserts happening at the same time (this bit of code is getting run simultaneously via backgrounds jobs).
I'm using Rails 4 and Postgres 9.3.1.