# 运营商 model : Carrier
# sim卡 model : SimCard
使用counter_cache 用来查询每个运营商下的sim卡的数量
1.增加字段(如果运营商已经有sim卡记录,则需要更新现有数量,两种方法)
class AddSimCardsCountToCarriers < ActiveRecord::Migration[5.2]
def change
add_column :carriers, :sim_cards_count, :integer, default: 0
#### 方法1直接用sql更新(sim_cards_count只读的)
execute 'update carriers set sim_cards_count =
(select count(*) from "sim_cards" where "sim_cards"."deleted_at" is null and "sim_cards"."carrier_id" = carriers.id)'
#### 方法2使用 reset_counters
Carrier.reset_column_information
Carrier.find_each do |carrier|
Carrier.reset_counters carrier.id, :sim_cards
end
end
end
2.关联
class SimCard < ApplicationRecord
belongs_to :carrier, counter_cache: true
end
class Carrier < ApplicationRecord
has_many :sim_cards, dependent: :destroy
end