简体   繁体   中英

Rails 4.2.2 counter_cache not updating

Using Rails 4.2.2 I created the following migration to add a counter_cache to the model Users, whenever I run rake db:migrate the counter shows the current :book_shelf_count correctly, but it doesn't update when it changes

add_shelf_book_count.rb

class AddShelfBookCount < ActiveRecord::Migration
  def self.up
    add_column :users, :book_shelf_count, :integer, default: 0

    User.reset_column_information

    User.find_each { |user| User.reset_counters user.id, :shelf_books }

  end

  def self.down
    remove_column :users, :book_shelf_count
  end

end

user.rb

class User < ActiveRecord::Base
  has_many :shelf_books, through: :shelves, dependent: :destroy
end

shelf.rb

class Shelf < ActiveRecord::Base
  has_many :shelf_books, dependent: :destroy
  belongs_to :user, counter_cache: :book_shelf_count
end

shelf_book.rb

class ShelfBook < ActiveRecord::Base
  belongs_to :shelf
end

The problem was that a ShelfBook was created or destroyed independently from the Shelf,so there is no way to update the counter_cache from the Shelf. In order to fix it I needed to implement a Increment Counter and Decrement Counter method in the shelf_book.rb

class ShelfBook < ActiveRecord::Base
  belongs_to :shelf
  after_create :increment_counter_cache
  after_destroy :decrease_counter_cache

  def increment_counter_cache
    User.increment_counter(:book_shelf_count, find_user)
  end

  def decrease_counter_cache
    User.decrement_counter(:book_shelf_count, find_user)
  end

  def find_user
    Shelf.find(self.shelf_id).user
  end

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