Jonathan Allard
Jonathan Allard

Reputation: 19249

Using other type than serial integer for Activerecord primary key

My data models often require their primary key to be another type than just a vanilla auto-incrementing integer. However, Rails/AR makes it not totally clear how to change that as the default.

How can I use another type than integer as my primary key in Activerecord?

Upvotes: 1

Views: 780

Answers (1)

Jonathan Allard
Jonathan Allard

Reputation: 19249

Caveat: Apart from Rails Master (yet unreleased—PR #18228), schema.rb won't remember the column type, so the feature isn't working for the moment. Workarounds are described here.

I was looking at documentation today as this is something I've been struggling with for a long time, and I came across t.primary_key:

primary_key(name, type = :primary_key, options = {})

Appends a primary key definition to the table definition. Can be called multiple times, but this is probably not a good idea.

So you just have to specify your migration as such, with id: false, and your primary key with the name and type of your choice:

class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags, id: false do |t|
      t.primary_key :name, :string

      t.timestamps null: false
    end

    # Alternative awkward-er syntax
    # create_table "tags", primary_key: "name", id: "string" do
  end
end

Your model will even automagically infer the primary key column name from the schema. Yay!

Upvotes: 1

Related Questions