使用Rails 4.2.2我创建了以下迁移以向模型Users添加counter_cache,每当我运行rake db:migrate时,计数器会正确显示当前:book_shelf_count,但是当它更改时它不会更新< / p>
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
答案 0 :(得分:0)
问题是ShelfBook是独立于Shelf创建或销毁的,因此无法从Shelf更新counter_cache。为了解决这个问题,我需要在 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