我正在添加一个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
endSQL:
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。我检查了Rails4的源代码(我使用的是Rails3),update_counters还没有修复。我将重新打开ActiveRecord::CounterCache.update_counters并尝试取消它的作用域。
发布于 2013-07-06 03:47:43
如前所述,您的默认作用域正在将您绊倒。有一种更好的方法来避免迁移中的此类问题:在迁移的范围内重新定义模型:
class MigrateFooToBar < ActiveRecord::Migration
class Foo < ActiveRecord::Base; end
def up
# ...
end
end然后当你从up中引用Foo时,你引用了限制无效和默认作用域MigrateFooToBar::Foo,它让你从A)必须太多地了解你的模型和B)当你的团队中的其他人运行你的迁移时迷惑了他们。
发布于 2013-07-06 03:43:46
Thx Baldrick我是rails新手和未作用域的工作:
Benefit.unscoped.update_counters b.id, :benefit_rows_count => b.benefit_rows.lengthhttps://stackoverflow.com/questions/17494708
复制相似问题