Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Rails migration, is it possible to indicate that a newly added column should be before or after an existing column in the table?

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?

like image 324
pez_dispenser Avatar asked May 19 '09 03:05

pez_dispenser


2 Answers

Use :after => :another_column_name, e.g.:

change_table :users do |t|
  t.integer :like_count, :default => 0, :after => :view_count
end
like image 151
ohho Avatar answered Sep 30 '22 18:09

ohho


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.

like image 45
jess Avatar answered Sep 30 '22 18:09

jess