In a Rails migration, can you indicate that the newly added column should be before or after the existing column in the table?

Let's say I create a table in a Rails migration, specifying to omit the identifier 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 decided that I wanted to add an identifier column as a primary key in order to 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 migration, it looks like this:

 category_id post_id id 

The id column is at the last position in the table, whereas usually the id column will be the first.

Is there a way to change the ChangeCategoriesToRichJoin migration to insist on creating an id column before the category_id column in the table?

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

+6
ruby-on-rails migration
source share
3 answers

I couldn’t put the columns in order myself, but with Rails you can roll back, modify the old migration file to add new columns in the desired order, and then reconfigure the old migration, including the new field. It's not entirely perfect, but easy to wrap and roll back, it can work if you have enough OCD to require column ordering .: P

I am not an expert, but I read a lot of the Rails documentation (and more recently) and cannot remember how to find a solution for this.

+1
source share

Use :after => :another_column_name , for example:

 change_table :users do |t| t.integer :like_count, :default => 0, :after => :view_count end 
+5
source share

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

+1
source share

All Articles