How to set default 'uuid-ossp' extension to all migration files?
I'm using ruby 2.1 and rails 4
Rails 4 has native support for the type UUID (Universally Unique Identifier) in Postgres. Here I will describe how you can use it for generating
UUIDs without doing it manually in your Rails code.
First you need to enable the
class CreateUuidPsqlExtension < ActiveRecord::Migration def self.up enable_extension "uuid-ossp" end def self.down disable_extension "uuid-ossp" end end
You can use a
UUID as a
create_table :translations, id: :uuid do |t| t.string :title t.timestamps end
In this case the Translations table will have a UUID as ID and it is autogenerated. The uuid-ossp extension in Postgresq has different algorithms how the UUID is generated. Rails 4 uses v4 per default. You can read more about these algorithms here: http://www.postgresql.org/docs/current/static/uuid-ossp.html
However, sometimes you don't want to have the UUID as ID replacement and instead have it in a separate column:
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration def up add_column :translations, :uuid, :uuid end def down remove_column :translations, :uuid end end
This will create a
UUID column, but the UUID will not be autogenerated. You have to do it yourself in Rails with SecureRandom. However, we think that this is a typical database responsibility. Fortunately, the default option in
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration def up add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()" end def down remove_column :translations, :uuid end end
UUID will be created
automatically, also for existing records!
I hope this help you to understand.. If this post satisfied you to understand UUID then kindly up-vote this answer... ;) via Helmut