为什么我的 Rails 迁移 "successfully" 更新但实际上没有更改记录?

Why is my Rails migration "successfully" updating but not actually changing records?

这是第一次。我正在尝试 运行 为我的 Rails 应用程序 (v4.2.0) 进行迁移,虽然迁移成功,但它实际上并没有改变任何东西。具体来说,我正在尝试为 table 实现 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

最后,您可以看到 SQL UPDATE 命令除了更改第一条记录(有 8 条评论)上的 updated_at 列外没有做任何事情,尽管传递了 comments_count 我的属性散列中的值:

D, [2015-02-13T09:15:54.997805 #68245] DEBUG -- :   SQL (0.3ms)  UPDATE "questions" SET "updated_at" =  WHERE "questions"."id" =   [["updated_at", "2015-02-13 16:15:54.992779"], ["id", 1]]

我确保在更新任何记录之前调用 reset_column_information,但它似乎没有任何效果。最近(甚至过去几天)我已经做过很多次了,我在这里用头撞墙。

我不确定您的版本为什么会失败 - 它看起来不错。不过,您可能想尝试 canonical version of populating counters:

Question.reset_counters(question.id, :comments)

代替update!