Adding a primary key id to table in rails

Just a quick little tip in case someone searches for it.

I have a table that was used for a has_and_belongs_to_many (habtm) relationship – which was great earlier on. As the application grew, needed to change to a has_many :through (hmt) relationship – using this table as a model etc. Now. initially, I used “:id => false” when creating the habtm join table (Mahmoud tells you why).

But one needs an primary key id on hmt join tables. So created a migration:
def self.up
add_column :table_name, :id, :primary_key
end

def self.down
remove_column :table_name, :id
end

And it added an id column to the table in the correct data type (integer) and gave id values to the existing records. sweet.

Also note that you don’t have to give the :id column a datatype, as to rails :primary_key is a datatype.

About these ads

15 thoughts on “Adding a primary key id to table in rails

  1. What database and adapter are you using? I’m pretty sure I’ve done this before with postgresql, but it doesn’t appear to work out-of-the-box for Oracle with the oracle_enhanced adapter :(

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s