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:
<p>
  <%= f.label :assign_to_container %>
  <%= f.collection_select :container_id, Container.all, :id, :title %>
</p>

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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to