(追記) 経緯:attr_read
はじめに、counter_ca cheの使い方
例えば、Blogテーブルにarticles_c
1 class Article < ActiveRecord::Base 2 belongs_to :blog, :counter_ca che => true
経緯
Rails2.0からカウンターキャッシュカラム(ex Blog#articles_c
1 #NG for Rails2.0 2 blog.update_attribute :articles_c ount, total
本題、migrationでの注意
- カラム名は複数形_count(ex. articles_c
ount)がデフォルト - カラム名のカスタマイズは、:counter_c
ache => :my_custom _counter - カラムはdefault => 0
- 既存のテーブルでcounterカラムを追加する場合はupdate_cou
ntersを使う
1 def self.up 2 add_column:blogs, :articles_c ount, :integer, :default => 0 3 4 Blog.find(:all).each do |blog| 5 Blog.update_cou nters(blog.id, :articles_c ount => blog.articles.count) 6 end
reference
posted by
satoko
on Tue 15 Jan 2008
at 00:40
with
2 comments
update_counters覚えた。 どうもです。 凄く細かいですけど
blog.articles.lengthだとarticles全部ロードしちゃうので、 blog.articles.countの方がいいと思われます。:)
nog, ありがとー!修正しましたっ