4

I created a migration that simply adds a new column, but I want it to be added before the created_at and updated_at columns, is there a way to specify in which position the new column is created ?

I searched and only found someone saying to use the :after option in add_column, but it doesn't do anything. then I looked in the rails api docs and found no such option.

Gal Ben-Haim
  • 17,433
  • 22
  • 78
  • 131
  • 1
    Why does it matter? I don't know anything about an :after option but if you are still in development and you don't have a problem with losing the data stored in your tables, you could always drop that table, and create it from scratch with all the attributes, without needing a migration to add certain columns. – Ashitaka Jan 28 '12 at 16:07
  • Just out of curiosity: does that have any impact on smth other than visual readability of the table? – KL-7 Jan 28 '12 at 17:45
  • I want it for better visual readability of the table, but while searching for a solution I found some blog post about performance effects – Gal Ben-Haim Jan 28 '12 at 17:51
  • @GalBen-Haim, can you share a link to the blog post? – KL-7 Jan 29 '12 at 14:19
  • here you go - http://explainextended.com/2009/05/21/choosing-column-order/ – Gal Ben-Haim Jan 29 '12 at 20:14

2 Answers2

5

After option works well for me

add_column :table_name, :column_name, :type, :after => :column_name

Also look at this question.

Community
  • 1
  • 1
Mikhail Nikalyukin
  • 11,867
  • 1
  • 46
  • 70
2

From my research, the :after option does not work for SQLite or Postgres, as these DBMSs do not allow such operation. However, the option works for MySQL.

References:

  1. SQLite: https://www.sqlite.org/lang_altertable.html - this basically tells you to create a new table with correct column ordering, then copy data over.

  2. Postgres: https://wiki.postgresql.org/wiki/Alter_column_position

konyak
  • 10,818
  • 4
  • 59
  • 65