如何在 Rails 迁移中将位置列添加到现有数据库记录的 acts_as_list?

How to add position column to acts_as_list on existing database records in Rails migration?

我看过How to change a nullable column to not nullable in a Rails migration? for the problem of adding a non-nullable column to an existing database table with existing records. As such, I am thinking of doing this to add position sortability to the model using acts_as_list:

class AddPositionToArticles < ActiveRecord::Migration[6.1]
  def change
    add_column :articles, :position, :integer
    Article.where(position: nil).each do |article|
      article.position = 0
      article.save!
    end
    change_column :articles, :position, :integer, null: false
  end
end

但是,这是不正确的,因为 position 需要根据相对于 user 记录的定位进行递增,所以 user.articles 是根据预定义的位置排序的。

如何在迁移中执行此操作?当我在文章中添加 acts_as_list 时会自动发生吗?如此简单,我需要做的就是重新保存迁移中的记录(而不是设置位置)?

如何确保它们的放置顺序与开始时的顺序相同?

class AddPositionToArticles < ActiveRecord::Migration[6.1]
  def change
    add_column :articles, :position, :integer
    User.find_each do |user|
      user.articles.order(created_at: :asc).find_each.with_index do |article, index|
        article.update_columns(position: index)
      end
    end
    change_column :articles, :position, :integer, null: false
  end
end