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