Rails add_column有一个限制,默认使用Postgres函数

时间:2016-04-12 17:34:13

标签: ruby-on-rails postgresql ruby-on-rails-4 postgres-9.4

我尝试添加默认为生成的UUID的列,而不使用连字符作为varchar(32)。目前这是我的迁移所在:

add_column :users, :uuid, :string, limit: 32, default: "REPLACE(uuid_generate_v4(), '-', '')"

但似乎错误,因为它只是将其设置为字符串文本:

  

PG :: StringDataRightTruncation:ERROR:类型字符变化的值太长(32)

我似乎无法找到有关为sql语句设置默认值的正确文档,但在Rails 5中可能更简单(https://github.com/rails/rails/pull/20005

1 个答案:

答案 0 :(得分:1)

<强>更新

我能找到你的答案。 Active Record(显然)有一些postgresql特定的支持。如果您正在使用postgresql 9.4+和Active Record,则可以在架构中使用UUID。 There's an official Rails guide that describes how to do it here

原始回复

我不知道如何在数据库级别设置此项,但您可以将默认值添加到Active Record模型using a callback,如下所示:

class Model < ActiveRecord::Base
  before_create do
    if self.uuid.nil?
      self.uuid = REPLACE(uuid_generate_v4(), '-', '')
    end
  end
end