Rails 4 can be used to support the postgres of the UUID (universally unique Identifier, the unique identifier) type in the original ecosystem. Here, I'll describe how you can use it to generate a UUID without manually modifying any rails code.
First, you need to activate the postgres extension ' UUID-OSSP ':
Class Createuuidpsqlextension < activerecord::migration
def self.up
execute "CREATE EXTENSION \" Uuid-ossp\ ";"
End
def self.down
execute "DROP EXTENSION \ uuid-ossp\";
End End
You can replace it with a UUID as an ID:
Create_table:translations, ID:: UUID do |t|
T.string:title
t.timestamps
End
In this example, the translation table will derive a UUID as an ID from the dynamic generation of it. The algorithm used by the Postgresq UUID-OSSP extension is different from the algorithm that generates the UUID. Rails 4 uses the V4 algorithm by default. You can here: http://www.postgresql.org/docs/current/static/uuid-ossp.html See more details about these algorithms.
However, sometimes you do not want to use a UUID as an ID to replace it. So you can put it in a different column:
Class Adduuidtomodelsthatneedit < activerecord::migration
def up
add_column:translations: UUID,: UUID
End
def down
remove_column:invoices,: UUID
end
This creates a column that places the UUID, but the UUID is not generated automatically. You have to use securerandom in rails to build it. However, we consider this to be a typical database responsibility behavior. Thankfully, the default option in Add_column will help us achieve this behavior:
Class Adduuidtomodelsthatneedit < activerecord::migration
def up
add_column:translations: uuid,: UUID, :d efault => "uuid_generate_v4 ()"
end
def down
remove_column:invoices: UUID End
Now, the UUID can be created automatically. The same applies to existing records!