Table of content
Rails 4 has native support for the type UUID (Universally Unique Identifier) in Postgres. In this Div Bit 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 Postgres extension ‘uuid-ossp’:
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 ID replacement:
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 add_column helps:
class AddUuidToModelsThatNeedIt < ActiveRecord::Migration
def up
add_column :translations, :uuid, :uuid, :default => "uuid_generate_v4()"
end
def down
remove_column :translations, :uuid
end
end
Now the UUID will be created automatically, also for existing records!
Related articles
Dev Bit: How to add plugins to elasticsearch under Mac/Brew
Learn how to install Elasticsearch plugins on Mac with Homebrew, find the right libexec path, and verify plugins like Kopf or Elastic HQ.
Dev Bit: How to reuse matched value of regex in JavaScript's replace() function
JavaScript's replace() function has special $ references that can be used with regular expressions to replace (sub)strings. In this article, we provide a detailed overview of how it works.
Dev Bit: SQL word count & character count with Postgres
LingoHub uses Postgres and Elasticsearch to manage its extensive collection of text data. If you're wondering whether there's a way to conduct an SQL word count for translations, the answer is yes. In this article, we'll provide you with two SQL queries that can be used to determine the character and word count of a text column.