【发布时间】:2013-07-05 18:12:27
【问题描述】:
我正在添加一个 counter_cache,但我的迁移出错了。
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忽略默认范围:stackoverflow.com/a/4166950/1128103
标签: ruby-on-rails migrate