在rails4与postgresql中使用uuid作为主键

安装步骤

先确保已经安装了 ruby on rails 和 postgresql

rails new uuids —database postgresql
rails generate migration enable_uuid_ossp_extension
rails generate model document title:string author:string

打开postgresql的uuid-ossp插件

class EnableUuidOsspExtension < ActiveRecord::Migration
  def change
    enable_extension uuid-ossp
  end
end

设置migration

class CreateDocuments < ActiveRecord::Migration
  def change
   create_table :documents, id: :uuid, default: 'uuid_generate_v4()'  do |t|
      t.string :title
      t.string :author
      t.timestamps
    end
  end
end

运行migration

rake db:create
rake db:migrate

安装完成

在console里测试一下

rails c

irb(main):011:0> Document.create(title: “PostgreSQL UUID!”, author: “Fox ZoOL”)
=> #<Document id: “ec31b888-a491-49e7-afa9-ab59e9131d78”, title: “PostgreSQL rocks!”, author: “Fox ZoOL”, created_at: “2015-01-10 21:02:17”, updated_at: “2015-01-10 21:02:17”>

Tips

由于主键已经是uuid了, Document.firstDocument.last 的返回值会出错,需要重写一下scope

class Document < ActiveRecord::Base
  scope :first, -> { order(created_at).first }
  scope :last, -> { order(created_at DESC).first }
end
comments powered by Disqus