无法访问 rails 迁移中的 uuid 字段

Can't access uuid field in rails migration

我有一个名为 'products' 的 table(模型是产品),当 运行 在迁移上下文中时,我无法访问 :uuid 属性。迁移本身不会更改结构,但会访问并创建新对象来填充数据库。

这是迁移前 schema.rb 的片段:

  create_table "products", force: :cascade do |t|
    t.string   "title"
    t.string   "description"
    t.string   "price"
    t.uuid     "uuid"
  end

产品对象定义如下:

  class Product < ActiveRecord::Base
  end

现在 运行 在 rails 控制台/代码中工作正常:

p = Product.create!(:uuid => xxx)
puts p.uuid # => xxx
puts p.inspect # => Product(title: string, description: string, price: string, uuid: uuid)

但是在迁移上下文中 运行 - 相同的代码引发异常:

p = Product.create!(:uuid => xxx)
puts p.uuid # => undefined method `uuid' for <Product:0x007fea6d7aa058>/opt/rubies/2.2.0/lib/ruby/gems/2.2.0/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433
puts p.inspect # => Product(title: string, description: string, price: string)

缺少 uuid 属性!怎么了?

迁移后通常会刷新模型的架构。因此,即使创建了 uuid 字段,模型也不知道它。

您可以使用

强制刷新
Product.reset_column_information

但是,您代码中的问题表明您可能正在使用迁移功能在迁移本身内部创建记录。通常不建议这样做,因为迁移旨在更改数据库的架构,而不是数据。

您应该使用创建特定的 rake 任务来修改数据和 运行 迁移完成后的任务,例如从控制台。

Product.reset_column_information

在你的 Product.create 行之前。