LoginSignup
3
2

More than 5 years have passed since last update.

Railsの主キーでUUIDを使うメモ

Last updated at Posted at 2017-11-25

追記

RailsのモデルIDにUUIDを使う(翻訳)

こちらの方が正確で良さそうです。

リンク先にも書いてありますが、UUIDのidではActiveRecordのfirst, lastなどのメソッドが期待通りに動きません。
したがって、

     it '新規作成されたエントリーにリダイレクトされる' do
        post :create, params: { user_id: user, entry: valid_attributes }
        expect(response).to redirect_to(Entry.last)
     end

こういうテストが場合によって通らなくなりました。正しいかわかりませんが、Entry.order(:updated_at).last と修正して1番最新につくられたものを取得しています...


  • Rails 5.1.4
  • PostgreSQL 9.6.4

posts/63
comment/2 のように
パス内に記事数などが露出してしまうのが気持ち悪かったので主キーにuuidを使います

migrationファイルのcreate_tableの引数にid: uuidを指定

create_table :users, id: :uuid do |t|
  t.string :email
  ...
end

のような感じで・

[1] pry(main)> User.first
  User Load (0.4ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<User:0x00007fe81e37dd50
 id: "1fb04a9d-9006-4887-be85-48fe54d34d45",
 email: "admin@example.com",
...

IDが連番じゃなくなりました。

ローカルでは使えていたがherokuにpushしてからmigrateしようとすると function gen_random_uuid() does not exist と怒られるので、

 $ heroku pg:psql                                                                                                                      
=> CREATE EXTENSION "uuid-ossp";
=> CREATE EXTENSION pgcrypto;
=> \q
 $ heroku run rake db:migrate 
.....

一番初めの日程にマイグレーションファイルを作成すればよかったかもしれない (未確認)

class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
  def up
    enable_extension 'uuid-ossp'
    enable_extension 'pgcrypto'
  end
end

参考にさせていただいたページ

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2