Add Time by converting to Ruby for seconds

Asked

Viewed 120 times

3

I am trying to find the average difference between the creation date and the last update of the records of a table as follows:

tickets = Ticket.all.where('updated_at IS NOT NULL')
t = tickets.sum(:updated_at, conditions: 'updated_at.to_time') - tickets.sum(:created_at, conditions: 'created_at.to_time')

But this way you’re making a mistake, where I’m making a mistake?

I did so below and it worked; but I believe without doing this loop I would win in performance.

tickets = current_client.tickets.where('updated_at IS NOT NULL')
t = 0
tickets.each do |ticket|
  t += ticket.updated_at.to_time - ticket.created_at.to_time
end
  • What is the expected result? What is the result obtained?

  • The expected would be the average difference in seconds of the updated_at - created_at but it returns nothing, gives a query error.

  • I was thinking of an example with real data. If a = b - c, with b being 3 and c being 2, the expected would be 1 but a received -1.

1 answer

2


If the problem is performance, would do the operation directly in BD:

Ticket.average("updated_at - created_at")

If there are other conditions it gets something like:

Ticket.where(<suas condições>).average("updated_at - created_at")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.