Counter Cache for a column with conditions?

后端 未结 4 1653
旧时难觅i
旧时难觅i 2020-11-30 06:34

I am new to the concept of counter caching and with some astronomical load times on one of my app\'s main pages, I believe I need to get going on it.

Most of the coun

4条回答
  •  孤街浪徒
    2020-11-30 07:08

    You should not use "counter_cache" but rather a custom column :

    rails g migration AddCompletedProjectsCountToEmployees completed_projects_count:integer
    

    (add , :default => 0 to the add_column line if you want)

    rake db:migrate
    

    then use callbacks

    class Project < ActiveRecord::Base
      belongs_to :employee
    
      after_save :refresh_employee_completed_projects_count
      after_destroy :refresh_employee_completed_projects_count
    
      def refresh_employee_completed_projects_count
        employee.refresh_completed_projects_count
      end
    end
    
    class Employee
      has_many :projects
    
      def refresh_completed_projects_count
        update(completed_projects_count:projects.where(completed:true).size)
      end
    end
    

    After adding the column, you should initialize in the console or in the migration file (in def up) :

    Employee.all.each &:refresh_completed_projects_count
    

    Then in your code, you should call employee.completed_projects_count in order to access it

提交回复
热议问题