Skip to content

Issues with Rails built-in cache counter #44

Closed
seivan opened this Issue Nov 25, 2011 · 2 comments

2 participants

@seivan
seivan commented Nov 25, 2011

belongs_to :order, :counter_cache => :contributors_count

contributors_count is null in the response, but 1 in the model
Next request. It's 1 in the response and 2 in the model.

I've resorted to callbacks for this for now. But really like this out of the box.

Basically the attribute isn't set when the response is sent.

@fabrik42
Owner

Hey :)

I am able to reproduce you problem, but this is not a problem of acts_as_api but of the Rails counter_cache implementation.

The same behaviour appears when you use the common rendering methods of Rails:

class ItemsController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @item = @user.items.build(params[:item])

    respond_to do |format|
      if @item.save
        format.xml  { render :xml => @user, :status => :created }
      else
        format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
      end
    end        
  end

end

I think the problem is that @item.save will modify the user model in the after_create callback but ActiveRecord won't know its instances of the user are dirty now (@user.changed? returns false). If you reload the @user instance in the case above, it will show the correct count.

@fabrik42
Owner

Closing this for now.

@fabrik42 fabrik42 closed this Feb 11, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.