0

How can I specify after which field I want to add a new column? (I don't want the field added in at the bottom after the timestamps)

add_column :users, :is_active, :boolean

2 Answers 2

1

Here is how:

add_column :users, :is_active, :boolean, :after => :some_column

where :some_column is the name of the column you want to add :is_active after.

1

In general, you can't and you shouldn't care. Tables in relational databases don't really have any particular order; that's why you should always specify the columns when you INSERT and never say things like select * ... (yes, ActiveRecord does that but that but that doesn't mean that it is a good idea, just because AR jumps off a cliff doesn't mean you should, etc.).

If you insist on trying to do the database's job for it then the portable way is:

  1. Copy or rename the table to another table.
  2. Drop the original (unless you renamed in (1)).
  3. Create the new table with the columns in the order you want.
  4. Hope the database pays attention to your order in (3).
  5. Copy the data to from the table in (1) to the "new" table from (3).
  6. ...
  7. Profit.

If you're using the MySQL or MySQL2 database adapters, you can use the :after => :some_column option to add_column. If you're using SQLite or PostgreSQL, then see the portable way above. If you're using anything else then you'll have to read the adapater's documentation or source code to see what is supported.

But you should ask yourself why you think you want to do this before proceeding.

2
  • Yeah I think I was confused, using too many things. I can delete my comment to avoid confusing people.
    – Amala
    Commented Dec 1, 2011 at 14:34
  • @Amala: No worries, we'll just clean it all up and move on to more interesting things :) Commented Dec 1, 2011 at 18:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.