Rails add_column with a limit and default with Postgres Function

879 Views Asked by At

I'm trying to add a column that defaults to a generated UUID without the hyphens as a varchar(32). Currently this is what my migration has:

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

But it seems to error out because it's just setting that as string text:

PG::StringDataRightTruncation: ERROR: value too long for type character varying(32)

I can't seem to find proper documentation on setting a default value to an sql statement, but that it might be simpler to do in Rails 5 (https://github.com/rails/rails/pull/20005)

1

There are 1 best solutions below

4
On

UPDATE

Well I was able to find your answer. Active Record (apparently) has some postgresql specific support. If you're using postgresql 9.4+ and Active Record, you can make use of UUID's in your schema. There's an official Rails guide that describes how to do it here.

ORIGINAL RESPONSE

I don't know how to set this at the database level, but you can add a default to the Active Record model using a callback like so:

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