Search code examples
mysqlruby-on-railsquery-optimization

How to optimize this code


I have used this code in helper to display the count based on the status -

    def to_do_count
        Task.where(status: 0).count
    end 

    def in_progress_count
        Task.where(status: 1).count
    end

    def paused_count
        Task.where(status: 2).count
    end

    def completed_count
        Task.where(status: 3).count
    end

I need help to optimize this code as there are lot of repetitions.


Solution

  • Option 1

    def task_count(status)
      Task
        .where(status: { to_do: 0, in_progress: 1, paused_count: 2, completed_count: 3 }[status])
        .count
    end
    
    task_count(:to_do) 
    task_count(:in_progress)
    

    Option 2

    You can simplify it by using scopes

    class Task
      scope :to_do,           -> { where(status: 0) }
      scope :in_progress,     -> { where(status: 1) }
      scope :paused_count,    -> { where(status: 2) }
      scope :completed_count, -> { where(status: 3) }
    end
    

    Then helper can look like this:

    def task_count(status)
      Task.send(status).count
    end
    
    task_count(:to_do)