这是第一次。我正在尝试为我的Rails应用程序(v4.2.0)运行迁移,并且在迁移成功时,它实际上并没有改变任何东西。具体来说,我正在尝试为表实现counter_cache
字段,为已经有关联的记录分配起始值。
这是我的迁移:
class AddCommentsCountToQuestions < ActiveRecord::Migration
def up
# dump SQL to console so I can see what's going on
ActiveRecord::Base.logger = Logger.new(STDOUT)
add_column :questions, :comments_count, :integer, null: false, default: 0
Question.reset_column_information
Question.find_each do |question|
puts "updating record #{question.id} to have #{question.comments.count} comments"
# use update! instead of update so that migration performs rollback on failure
question.update!(comments_count: question.comments.count)
puts "record #{question.id} actually persisted with #{question.reload.comments_count} comments"
end
end
def down
remove_column :questions, :comments_count
end
end
我的控制台输出表明,在重新加载记录时,它没有保留comments_count
值:
updating record 1 to have 8 comments
record 1 actually persisted with 0 comments
updating record 2 to have 0 comments
record 2 actually persisted with 0 comments
updating record 3 to have 0 comments
最后,除非在我的属性中传递updated_at
值,否则您可以看到SQL UPDATE命令除了更改第一条记录上的comments_count
列(带有8条注释)之外没有做任何其他操作。散列:
D, [2015-02-13T09:15:54.997805 #68245] DEBUG -- : SQL (0.3ms) UPDATE "questions" SET "updated_at" = $1 WHERE "questions"."id" = $2 [["updated_at", "2015-02-13 16:15:54.992779"], ["id", 1]]
我确保在更新任何记录之前调用reset_column_information
,但似乎没有任何效果。我最近做了很多次(过去几天甚至),我在这里撞墙。
答案 0 :(得分:1)
我不确定你的版本失败的原因 - 看起来不错。不过,您可能还想尝试canonical version of populating counters:
Question.reset_counters(question.id, :comments)
取代update!