# Counter-cache AFTER database already populated

**URL:** <https://www.ruby-forum.com/t/counter-cache-after-database-already-populated/77378>\
**Category:** Rails\
**Created:** [November 27, 2006, 1:47pm UTC](https://www.ruby-forum.com/t/counter-cache-after-database-already-populated/77378 "2006-11-27T13:47:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [November 27, 2006, 1:47pm UTC](https://www.ruby-forum.com/t/counter-cache-after-database-already-populated/77378/1 "2006-11-27T13:47:19Z")

</div>

I need to use the counter-cache functionality in my model.  
I defined as stated the counter-cache =\> true; on the belongs\_to side  
and a xxx\_count column on the has\_many side.  
In my database this column is now 0.  
How can I ‘repair’ the count… as obviously it should be equal to the  
number of items already stored on the many side… ?  
should I write a procedure ? a specific action in my app ?  
btw : the table on the one side is 38’000 items… which exclude doing  
it by-hand !

kad

---

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [November 27, 2006, 5:12pm UTC](https://www.ruby-forum.com/t/counter-cache-after-database-already-populated/77378/2 "2006-11-27T17:12:01Z")

</div>

Kad,

If you want to initialize the counter cache after having modified the  
db schema, simply run set the value in the migration like:

class AddArticlesCounterCache \< ActiveRecord::Migration  
def self.up  
add\_column :blogs, :articles\_count, :integer

```
for blog in Blog.find(:all) do
  blog.articles_count = blog.articles.size
  blog.save
end

```

end

def self.down  
remove\_column :blogs, :articles\_count  
end  
end

Alain
