24

I tried to add a column to a table after a specific column in the table. Here is what I did:

rails generate migration add_reaction_id_to_patient_allergies reaction_id: integer :after => 'patient_id'

Here is what my migration file looks like:

class AddReactionIdToPatientAllergies < ActiveRecord::Migration
  def change
    add_column :patient_allergies, :reaction_id, :string
    add_column :patient_allergies, :integer, :string
    add_column :patient_allergies, :, :after
    add_column :patient_allergies, :=, :string
  end
end

I dont think the command went well. I see an '=' in the above file. I do not think it should be there. Can someone tell me if I missed anything?

If so , how do I undo the above?

Micheal
  • 2,272
  • 10
  • 49
  • 93

1 Answers1

58

I doubt it allowed you to actually rake db:migrate this migration, so you shouldn't have to roll back. Just remove the bottom three add_columns and replace the top one with

add_column :patient_allergies, :reaction_id, :integer, after: :patient_id

and it should be fine to migrate. For future reference, here's what that command you entered should look like:

rails generate migration add_reaction_id_to_patient_allergies reaction_id:integer

The space before integer made the generator think it was a new column. Sadly you can't use Ruby syntax (a => b) on the command line either.

piersadrian
  • 1,653
  • 12
  • 12
  • 1
    @michael Just to add one more thing to this great answer, to undo a successful but unwanted migration you can do rake db:rollback - this reverses the most recent migration. You can step further back by repeating it. I often find myself undoing to make small tweaks, such as setting default value or column order – Polsonby Jan 07 '14 at 11:28
  • 5
    The `:after` option doesn't look to be included in the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/Migration.html), at least for Rails 4.2.3. Found out after trying: the migration went ok but the ordering was not applied. – nandilugio Aug 18 '15 at 17:26
  • @nandinga It looks like the [ColumnDefinition](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L13) class in the latest Rails still supports the `after` option, though I haven't tested this on the last few releases of Rails. – piersadrian Aug 25 '15 at 22:36
  • 22
    Apparently this doesn't work if you're using Postgres. See http://dba.stackexchange.com/questions/3276/how-can-i-specify-the-position-for-a-new-column-in-postgresql – lacostenycoder Feb 05 '16 at 16:47