Apr6

Rails Tip: Primary Keys

Rails by default uses a system-generated primary key called “id” for all persisted objects. I personally like this (for the very reasons Dave Thomas outlines in the Rails book on pp. 286-287), but if you don’t, you can change it. Like Dave, I don’t recommend it, but here’s how if you must.

class Friend < ActiveRecord::Base
self.primary_key = "email"
end

Now the primary key of the Friend class is “email” and you must set this value before you can save the object. This is one caveat of being able to change the primary_key from the convention (but don’t complain, at least you can do it).

I chose this example to point out why I like using system-generated, non-model-related primary keys. Email address seems at first like a reasonable field to use for the primary key because they must be unique between people* and they don’t change (often). But they do change (for example if someone use’s their ISP for email and they change their ISP). If you use it as the primary key and your best friend moves from Boston to Idaho and gets a new email address, you have to update all of the places that it’s used as a foreign key (and in the case of your best friend, this may be quite a few places).

Stick to the default system-generated ID and you’ll be better off. But at least you can change the default if you must.

Composite Keys

Rails doesn’t support composite keys natively, but there are plugins available that accommodate this, such as Nic Williams CompositeKeys.
* In the case of a married couple who shares the same email address, you would not be able to include both the man and the woman (who might both be your friends) in your contact list.


No Responses to “Rails Tip: Primary Keys”

You can leave a response, or trackback from your own site.

 

Leave a Reply

You must be logged in to post a comment.

 

Recent Posts

Popular Categories

Grails Mac Rails Bible Code Coffee Candor

About

I’m a software engineer by day and even busier by night.  This blog contains my thoughts on subjects from the Bible to lines of code.  I write (and drink) Java, I’m learning Ruby and Rails and I read the King James Bible.  I’m hoping to move the country and buy a farm and stay home with my family to bring them up in the nurture and admonition of the Lord.