Altering the primary key in Rails to be a string

Though, I agree that this might be more trouble than it’s worth considering the extra effort of working against the defaults elsewhere, just in case you actually want to do what you’ve asked:

Create states migration:

class CreateStatesTable < ActiveRecord::Migration  
  def change
    create_table :states, id: false do |t|
      t.string :state, limit: 2
      t.string :name
      t.index :state, unique: true
    end
  end
end

states model:

class State < ActiveRecord::Base
  self.primary_key = :state
end

Note that before Rails 3.2, this was set_primary_key = :state instead of self.primary_key= see: http://guides.rubyonrails.org/3_2_release_notes.html#active-record-deprecations

Leave a Comment