Tutorial on using Ruby on Rails and PostgreSQL to automatically generate UUID _ruby topics

Source: Internet
Author: User
Tags postgresql uuid ruby on rails

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.