Torihaji's Growth Diary

Little by little, no hurry.

RailsのActiveRecordにおいてuuidをDBで使う

はじめに

やりたいことは PostgreSQLのDBにおいて使用する idを

uuid デフォルトにして云々するです。

何するか。

application.rbにおいて以下を記載。

    config.generators do |g|
      g.orm :active_record, primary_key_type: :uuid
    end

以下のmigrationファイルを作成し、適用。

class EnableExtensionForUuid < ActiveRecord::Migration[7.2]
  def change
    enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
  end
end

どうなるか

そうするとmigrationでmodel作る時に

 create_table :users, id: :uuid <= この記述が自動でつくようになります。

毎回手動で、これつけてもいいですけどだるい人はこれをやるべき。

終わりに

以上〜。