JQ Blog

カウンターキャッシュについて

カウンターキャッシュとは

  • Rails3からの機能で、以下のように設定することにより関連するテーブルのレコード数を簡単にカウントさせることができる

設定

1
2
3
4
5
6
7
class Survey < ApplicationRecord
  has_many :questions, class_name: "Question", foreign_key: :survey_id, dependent: :destroy
end

class Question < ApplicationRecord
  belongs_to :survey, class_name: "Survey", foreign_key: :survey_id, touch: true, counter_cache: :questions_count
end

のような関係を持つモデルの子モデルに

1
2
3
class Question < ApplicationRecord
  belongs_to :survey, class_name: "Survey", foreign_key: :survey_id, touch: true, counter_cache: :questions_count
end

counter_cache: :カラム名のように追加する
それからmigrationを追加する

1
rails g migration add_column_questions_count_to_qualitative_surveys

そこに

1
2
3
4
5
6
7
8
9
10
11
12
13
class AddColumnInquiresCountToSurveys < ActiveRecord::Migration[5.0]
  def change
    add_column :surveys, :questions_count, :integer, default: 0
  end

  reversible do |dir|
    dir.up do
      Survey.all.each do |survey|
        Survey.reset_counters(survey.id, :questions)
      end
    end
  end
end

default: 0を追加し、今持っている子モデルのカウントをセッティングする場合は上記のようにreset_countersメソッドを使って更新する consoleで確認してみたら

1
2
3
4
5
irb(main):001:0> survey = Survey.last
Survey Load (6.0ms)  SELECT  "surveys".* FROM "surveys" ORDER BY "surveys"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> #<Survey id: 83, title: "Survey_title_49", content: nil, created_at: "2017-02-08 10:26:51", updated_at: "2017-02-16 02:55:41", questions_count: 43>
irb(main):002:0> survey.questions_count
=> 43

のように確認できる