• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

(追記) 経緯:attr_readonlyを追加しました。

はじめに、counter_cacheの使い方

例えば、Blogテーブルにarticles_countカラムを持つことで、blog.articles.sizeをキャッシュし、増減はrailsが自動でやってくれます。 こんな感じ。

   1  class Article < ActiveRecord::Base
   2    belongs_to :blog, :counter_cache => true

経緯

Rails2.0からカウンターキャッシュカラム(ex Blog#articles_count)がどうやらattr_readonlyになったようで、migration内でupdate_attributeで数が更新できなったので、困った。エラーもでなくて、データで確認すると更新できてない状態。

   1  NG for Rails2.0
   2   blog.update_attribute :articles_count, total 

本題、migrationでの注意

  • カラム名は複数形_count(ex. articles_count)がデフォルト
  • カラム名のカスタマイズは、:counter_cache => :my_custom_counter
  • カラムはdefault => 0
  • 既存のテーブルでcounterカラムを追加する場合はupdate_countersを使う

   1    def self.up
   2      add_column :blogs, :articles_count, :integer, :default => 0
   3  
   4      Blog.find(:all).each do |blog|
   5        Blog.update_counters(blog.id, :articles_count => blog.articles.count)
   6      end

reference

http://josh.the-owens.com/archives/2007/11/03/rails-edge-change-how-to-add-a-counter-cache-to-an-existing-db-table/

posted by Png satoko on Tue 15 Jan 2008 at 00:40 with 2 comments

Comments:

Png Shingo Noguchi over 15 years ago.

update_counters覚えた。 どうもです。 凄く細かいですけど

Blog.update_counters(blog.id, :articles_count => blog.articles.length)

blog.articles.lengthだとarticles全部ロードしちゃうので、 blog.articles.countの方がいいと思われます。:)

Png satoko over 15 years ago.

nog, ありがとー!修正しましたっ

or Preview
Social Bookmarks
  • Delicious
  • B_entry308
  • Clip_16_12_w
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ