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


if you find yourself here... leave as quickly as you can and go to: Using Rails, how can I set my primary key to not be an integer-typed column?


In Rails 5.1 you can specify the type of the primary key at creation:

create_table :states, id: :string do |t|
# ...
end

From the documentation:

A Symbol can be used to specify the type of the generated primary key column.


I'm working on a project that uses UUIDs as primary keys, and honestly, I don't recommend it unless you're certain you absolutely need it. There are a ton of Rails plugins out there that will not work unmodified with a database that uses strings as primary keys.