Ruby on rails 在数据迁移中重写attr_readonly,以在现有记录上填充新的只读字段

Ruby on rails 在数据迁移中重写attr_readonly,以在现有记录上填充新的只读字段,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我已将UUID字段添加到现有模型中。我希望它是只读的,所以不能更改 型号: class Token < ActiveRecord::Base attr_readonly :uuid before_create :set_uuid, on: create def set_uuid self.uuid = SecureRandom.urlsafe_base64(8) end end class标记

我已将UUID字段添加到现有模型中。我希望它是只读的,所以不能更改

型号:

class Token < ActiveRecord::Base
  attr_readonly :uuid
  before_create :set_uuid, on: create

  def set_uuid
    self.uuid = SecureRandom.urlsafe_base64(8)
  end
end
class标记
但是,我想用UUID填充现有记录。我无法通过默认值执行此操作,因为它们不是动态生成的

我可以在模型中编写一个自定义验证器,但当我只想在数据迁移中重写attr_readonly时,这似乎有些过头了

目前,我的数据迁移不会将现有值的值从零更改为零

数据迁移:

class AddUuidToTokens < ActiveRecord::Migration
  def self.up
    Token.all.each do |token|
    if token.uuid.nil?
      token.uuid = SecureRandom.urlsafe_base64(8)
      token.save!
    end
  end
end
类AddUuidToTokens
您可以在迁移中覆盖
令牌
类本身:

class AddUuidToTokens < ActiveRecord::Migration
  class Token < ActiveRecord::Base
  end

  def self.up
    Token.where(uuid: nil).find_each do |token|
      token.update_columns(uuid: SecureRandom.urlsafe_base64(8))
    end
  end
end
类AddUuidToTokens
小的改进:只加载不带
uuid的记录,而不是根据
nil?
检查所有记录,您可以在迁移中覆盖
标记
类本身:

class AddUuidToTokens < ActiveRecord::Migration
  class Token < ActiveRecord::Base
  end

  def self.up
    Token.where(uuid: nil).find_each do |token|
      token.update_columns(uuid: SecureRandom.urlsafe_base64(8))
    end
  end
end
类AddUuidToTokens
小的改进:只加载没有
uuid
的记录,而不是对照
nil?
检查所有记录