简体   繁体   中英

Rails counter_cache update too slow?

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.

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.

Ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM