Reputation: 13378
Using Rails 3. I have the following:
# shop.rb
class Shop < ActiveRecord::Base
belongs_to :country, :touch => true, :counter_cache => :total_shops
...
end
# shops_controller.rb
class ShopsController < ApplicationController
def create
...
@shop.save
@new_total_shops = @country.total_shops
end
end
Let's say initial @country.total_shops
is 2
, then when it's created, it should be incremented to 3
, but when I try abort(@country.total_shops)
right after the line @shop.save
, it still shows 2
. When I refresh the page, it shows 3
. I guess it just gets updated a bit slow.
How can I get the latest value quickly?
Thanks.
Upvotes: 0
Views: 429
Reputation: 18773
My guess is that since you've (I assume) already loaded the Country
instance before you save the new shop, you're seeing the total_shops
value as it was when the country was loaded.
I.e. you've got the old value in memory, even though the underlying database values have changed.
Try this:
@shop.save
# reload the country instance from the database
# to get the updated counter cache value
@country.reload
@new_total_shops = @country.total_shops
Upvotes: 1