我将 Rails 4.2.7 与 PostGres 结合使用。我创建了几个表,所有表都有数字主键。下面是我的一个 Rails 迁移示例
class CreateMyObjects < ActiveRecord::Migration
def change
create_table :my_objects do |t|
t.string :name
t.date :day
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
我在这张表中没有任何数据,但我有几个通过外键链接到它的表。我想将主键从数字主键更改为 GUID (UUID),因为我将遇到在两个不同的数据库中创建数据的情况,并且我不希望出现主键冲突结合数据。如何创建将主键的类型从数字更改为我的 UUID 类型的迁移,以及如何更新链接到表的所有外键?
谢谢,-戴夫
最佳答案
class ChangePrimaryKey < ActiveRecord::Migration
def change
remove_column :my_objects, :id # remove existing primary key
add_column :my_objects, :uuid, :string
execute "ALTER TABLE my_objects ADD PRIMARY KEY (uuid);"
end
end
class MyObject < ActiveRecord::Base
self.primary_key = :uuid
end
至于自动递增 - 不,Rails 不会为您递增您的字符串 id
,因此您必须自己处理它。
您可以在模型中使用 before_create
回调:
before_create :generate_uuid
private
def generate_uuid
loop do
self.uuid = SecureRandom.base64(16) # or other way to generate uniq string
break unless self.class.find_by(uuid: uuid) # make sure you don't repeat the uuid
end
end
你也可以给primary_key列添加约束,比如not null
约束,uniqueness
,length
等
关于ruby-on-rails - 在 Rails 中,如何创建将更改主键类型的迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39215001/