(追記) 経緯:attr_readonlyを追加しました。
###はじめに、counter_cacheの使い方
例えば、Blogテーブルにarticles_countカラムを持つことで、blog.articles.sizeをキャッシュし、増減はrailsが自動でやってくれます。
こんな感じ。
rails>>
class Article < ActiveRecord::Base
belongs_to :blog, :counter_cache => true
<<--
###経緯
Rails2.0からカウンターキャッシュカラム(ex Blog#articles_count)がどうやらattr_readonlyになったようで、migration内でupdate_attributeで数が更新できなったので、困った。エラーもでなくて、データで確認すると更新できてない状態。
rails>>
#NG for Rails2.0
blog.update_attribute :articles_count, total
<<--
###本題、migrationでの注意
- カラム名は複数形_count(ex. articles_count)がデフォルト
- カラム名のカスタマイズは、:counter_cache => :my_custom_counter
- カラムはdefault => 0
- 既存のテーブルでcounterカラムを追加する場合はupdate_countersを使う
rails>>
def self.up
add_column :blogs, :articles_count, :integer, :default => 0
Blog.find(:all).each do |blog|
Blog.update_counters(blog.id, :articles_count => blog.articles.count)
end
<<--
posted by
satoko on Wed 16 Jan 2008 at 11:58 with 2 comments
凄く細かいですけど
>Blog.update_counters(blog.id, :articles_count => blog.articles.length)
blog.articles.lengthだとarticles全部ロードしちゃうので、 blog.articles.countの方がいいと思われます。:)