Skip to main content
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Counting number of messages for a mailbox. How to optimize the following code? over several periods

Source Link
kirqe
  • 103
  • 5

Counting number of messages for a mailbox. How to optimize the following code?

The idea is to return a number of messages received today, this week, this month.

  def index
    @mailboxes = current_user.mailboxes
    @today, @month, @week, @all_time = 0, 0, 0, 0

    @mailboxes.each do |mailbox|
      @today += mailbox.messages.today.length
      @month += mailbox.messages.week.length
      @week += mailbox.messages.month.length
      @all_time += mailbox.messages.length
    end
  end

week, month scopes are similar to the following one

  scope :today, -> { where(created_at: ((Time.zone.now - 24.hours)..Time.zone.now)) }