Saturday, January 31, 2015

Creating a Rails Model with a Non-default Primary Key

One of the main Rails philosophies is "convention over configuration". This works great most of the time, but sometimes it's best to do something outside of convention. One example is the primary key for models. Sometimes you want the key to be something other than ID; maybe you want it to be the ID of a related model.

This is possible to set up in a migration, you just need to do a few important things:
  • Set id: false on the create_table line
  • Set your new primary key to null: false
  • Add a unique index on your new primary key
Here is an example:

 class CreateBearHabitats < ActiveRecord::Migration  
   def change  
     create_table :bear_habitats, id: false do |t|  // prevents a default ID column from being created
       t.belongs_to :bear, null: false //creates a bear_id column that can not be null
       t.string :habitat  
     end  

     add_index :bear_habitats, :bear_id, unique: true // ensures that the bear_id column is unique
   end  
 end  
This BearHabitat model will now use bear_id as a primary key instead of the standard id.