LoginSignup
1
1

More than 5 years have passed since last update.

Rails:Modelに代入したらcounter cacheが倍になった

Posted at

経緯

既存のFugaモデル全てに新しく作ったHogeモデルを持たせたい。

fuga.rb

class Fuga < ActiveRecord::Base
  belongs_to :hoge, counter_cache: true
end

hoge.rb

class Hoge < ActiveRecord::Base
  has_many :fugas
end

db/migrate/add_fugas_counter_to_hoge.rb

class AddFugasCounterToHoge < ActiveRecord::Migration
  def change
    add_column :fugas, :hoge_id, :integer
    add_column :hoges, :fugas_count, :integer, default: 0, null: false
  end
end

こんなscriptを書いた
bin/add_hoge_to_exist_fugas.rb

hoge = Hoge.new()
fugas = Fuga.all

fugas.each{|fuga|
  fuga.hoge = hoge
  fuga.save!
}

結果、hoge.fugas_countがfugas.sizeの2倍になった。

解決法

hoge = Hoge.new()
fugas = Fuga.all

fugas.each{|fuga|
  fuga.hoge_id = hoge.id
  fuga.save!
}

で正常にカウントされた。

また、正常にカウントされていないものは
bin/fix_fugas_counter_of_hoge.rb

Hoge.find_each{|hoge|
  Hoge.reset_counters(hoge.id, :fugas)
}

を実行することで直った。

どうして2倍になったのかはわからずじまいなので知っている方教えて下さい。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1