親モデル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