views:

350

answers:

2

Let's say I create a table in a Rails migration, specifying to omit the ID column:

create_table :categories_posts, :id => false do |t|
  t.column :category_id, :integer, :null => false
  t.column :post_id, :integer, :null => false
end

Later I decide I want to add an ID column as a primary key so I create a new migration:

class ChangeCategoriesToRichJoin < ActiveRecord::Migration
  def self.up
    add_column :categories_posts, :id, :primary_key
  end

  def self.down
    remove_column :categories_posts, :id
  end
end

But when I look at the table after I migrate, it looks like this:

category_id
post_id
id

The id column is in the last position in the table, whereas normally an id column would be first.

Is there a way to change the ChangeCategoriesToRichJoin migration to insist on the id column being created BEFORE the category_id column in the table?

Or do I need to drop the table and add the column in the "create table" definition?

+2  A: 

I haven't been able to put the columns in order, myself, but with Rails you can rollback, alter the old migration file to add the new columns in the order you want, then re-migrate up the old migration including the new field. It's not exactly ideal, but the ability to migrate and rollback easily, it can work if you're OCD enough to require column order. :P

I am not an expert, but I've read a lot of Rails documentation (and very recently) and can't recall finding a solution for this.

jess
That was my suspicion. Thanks for confirming.
pez_dispenser
A: 

Also see this question, with a possible solution: In a Rails Migration (MySQL), can you specify what position a new column should be?

magnushjelm