LoginSignup
7
7

More than 5 years have passed since last update.

counter_cacheを使って子モデルの件数を自動で親モデルのカラムに格納する

Last updated at Posted at 2014-05-05

親モデルParentと子モデルChildがあり、子モデルの件数を親モデルで持つ場合、counter_casheが便利。

やり方は、以下。
これで子モデルを作るたびに、自動的にchild_countをインクリメントしていってくれる。

parent.rb
# == Schema Information
# Table name: good_reviews
#  id           :integer          not null, primary key
#  child_count  :integer          default(0), not null

class Parent < ActiveRecord::Base
 has_many :child

end
child.rb
# == Schema Information
# Table name: good_reviews
#  id           :integer          not null, primary key
#  parent_id    :integer

class Child < ActiveRecord::Base
  belongs_to :parent, counter_cache: :child_count

end
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7