我正在添加一個counter_cache,並且我的遷移出現錯誤。Rails update_counters與default_scope錯誤
def up
add_column :benefits, :benefit_rows_count, :integer, :default => 0
Benefit.reset_column_information
Benefit.find(:all).each do |b|
Benefit.update_counters b.id, :benefit_rows_count => b.benefit_rows.length
end
end
SQL:
UPDATE "benefits" SET "benefit_rows_count" = COALESCE("benefit_rows_count", 0) + 0
WHERE "benefits"."id" IN (SELECT "benefits"."id"
FROM "benefits"
WHERE "benefits"."id" = 1
ORDER BY benefit_types.position, benefit_types.name, id)
這ORDER BY,裏面的更新是因爲default_scope的,它失敗的遷移。
不幸的是,當我更新記錄時,執行回調update_counters時出現同樣的錯誤。我讀過一些說,應該避免default_scope的帖子。我檢查了Rails 4源代碼(我使用Rails 3),並且update_counters還沒有被修復。我打算重新打開ActiveRecord :: CounterCache.update_counters並嘗試對其進行調整。
你在遷移文件中放了什麼?你可以在Rails 3中用'unscoped'來忽略默認的作用域:http://stackoverflow.com/a/4166950/1128103 – Baldrick