原因:在两个模型之中,比如author模型和book模型,author有很多book,需要统计author.books.size的数量,这条语句会执行数据库的count查询,为了避免使用count查询,可以在author中添加books_count字段,具体代码执行如下:

#model
class Book < ApplicationRecord
  #需要添加counter_cache语句
  belongs_to :author, counter_cache: true
end
class Author < ApplicationRecord
  has_many :books
end

#添加字段books_count到author中
class AddCommentsCountToTopics < ActiveRecord::Migration[5.1]
  def change
    add_column :authors, :books_count, :integer, default: 0
  end
end

#变更counter_cache的字段(用的比较少)
class Book < ApplicationRecord
  belongs_to :author, counter_cache: :count_of_books #变更默认的字段,那么在author中需要添加count_of_books字段
end
class Author < ApplicationRecord
  has_many :books
end

更新每个author中的books_count中的值

#使用reset_counters方法进行
class AddCounterCacheToCompanies < ActiveRecord::Migration[5.0]
  def change
    add_column :companies, :users_count, :integer, default: 0
    Company.find_each { |company| Company.reset_counters(company.id, :users) }
  end
end

上面是在has_many中使用,但是在through中最好不要使用,会出现各种问题

#下面的代码不要使用,即在has_many through中下面的代码是会报错的
class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  #这样子指定会报错
  belongs_to :physician, counter_cache: :physicians_count
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

在has many through 中使用counter的正常方法,使用callback方式

示例文章

results matching ""

    No results matching ""