# How to update counter\_cache when updating a model?

**URL:** <https://www.ruby-forum.com/t/how-to-update-counter-cache-when-updating-a-model/189467>\
**Category:** Rails\
**Created:** [June 1, 2010, 2:07pm UTC](https://www.ruby-forum.com/t/how-to-update-counter-cache-when-updating-a-model/189467 "2010-06-01T14:07:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![vince](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/b5e925/32.png) [@vince](https://www.ruby-forum.com/u/vince)\
**Post date:** [June 1, 2010, 2:07pm UTC](https://www.ruby-forum.com/t/how-to-update-counter-cache-when-updating-a-model/189467/1 "2010-06-01T14:07:44Z")

</div>

I have a very simple relationship - a container has many items

containers(title, items\_count)  
items(container\_id, title)

class Item \< ActiveRecord::Base  
belongs\_to :container, :counter\_cache =\> true  
end

My views/items/edit.html.erb looks like this:

\<%= f.label :assign\_to\_container %\> \<%= f.collection\_select :container\_id, Container.all, :id, :title %\>

And my items\_controller.rb looks like this:

class ItemsController \< ApplicationController  
def edit  
@item = Item.find(params[:id])  
end

def update  
@item = Item.find(params[:id])  
if @item.update\_attributes params[:item]  
flash[:notice] = “Item updated”  
redirect\_to items\_path  
else  
render :action =\> :edit  
end  
end  
end

My problem is that the counter cache (container.items\_count) is not  
getting updated when I update an item’s container. Anyone know what  
I’m doing wrong? I’m on Rails 2.3.5

p.s. I got it to “work” by add this to my update action, but it seems  
like there should be a cleaner solution

def update  
@item = Item.find(params[:id])  
@item.container = Container.find(params[:item][:container\_id])  
unless params[:item][:container\_id].blank?  
if @item.update\_attributes params[:item]  
flash[:notice] = “Item updated”  
redirect\_to items\_path  
else  
render :action =\> :edit  
end  
end
