0

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)

Tom Prats
  • 7,364
  • 9
  • 47
  • 77

1 Answers1

1

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
John
  • 9,249
  • 5
  • 44
  • 76
  • Would that run? My example was postgres functions and not ruby but the way I do it in ruby is in `before_create` (so only runs once) with `self.uuid ||= SecureRandom.uuid.gsub("-", "")` (`||` so that you can choose to set it manually). I'm mostly just interested in being able to do it in the postgres side of things – Tom Prats Apr 13 '16 at 03:38
  • You're totally right, before validate would not work as it would also fire on update. I have no idea about the function, I was just copying from your example. That being said, since you're using postgresql (as evinced by your error statement), I found your solution and updated my answer. – John Apr 13 '16 at 04:31
  • Wow, reading through all of that link, Active Record actually supports a lot of postgresql specific features. – John Apr 13 '16 at 04:48
  • Since you obviously have some sql knowledge, don't suppose you know the answer to this question I posted earlier? http://stackoverflow.com/questions/36580266/order-by-columns-that-are-sometimes-empty-using-active-record-rails – John Apr 13 '16 at 04:49