0

I use Rails 4, SQLite version 3.8.2 and I would like to add new column to my db. I create new migration:

rails g migration AddFooToStudents foo:string

so I get then :

class AddFooToStudents < ActiveRecord::Migration
  def change
    add_column :students, :foo, :string, after: :name
  end
end

then I run migration:

rake db:migrate

== 20150803095305 AddFooToStudents: migrating
=================================
-- add_column(:students, :foo, :string, {:after=>:name})
-> 0.0009s
== 20150803095305 AddFooToStudents: migrated (0.0011s)
========================

Everythink seems to be OK, in database has been added foo column but instead of after name column, it has been added at the end of table

ActiveRecord::Schema.define(version: 20150803095305) do
create_table "students", force: :cascade do |t|
  t.string   "name"
  t.string   "lastname"
  t.integer  "age"
  t.datetime "created_at",                       null: false
  t.datetime "updated_at",                       null: false
  t.string   "second_name", default: "Untitled"
  t.string   "foo"
end
end

I completely don't know what I do wrong

mike927
  • 682
  • 1
  • 8
  • 25
  • You are not doing anything wrong. This is a normal working behaviour of running migrations. `foo` column has been appended to the table. If you absolutely have to reorder columns, [here](http://stackoverflow.com/questions/18899011/rails-4-migration-how-to-reorder-columns) is a perfect answer that already exists. – Tim Aug 03 '15 at 10:08
  • please add your database back-end. `mysql`, `pg`, `sqlite`? – Roman Kiselenko Aug 03 '15 at 10:12

2 Answers2

3

You're using the after option, and so you could reasonably expect it to put it after :name.

However, this isn't documented very well (if at all) but the after option only works in some DBMSs (possibly only MySQL).

What i do is add my own sql to do this, after the add_column call, like so:

add_column :students, :foo, :string
ActiveRecord::Base.connection.execute("ALTER table students MODIFY COLUMN foo varchar(255) AFTER name")  

Your SQL will need to be DBMS-specific, ie tailored to MySql, PostGresql, SQLite etc.

Max Williams
  • 32,435
  • 31
  • 130
  • 197
0

Well, SQLite does not handle AFTER syntax so in this situation the best solution is leave unchanged order of columns or create new table.

mike927
  • 682
  • 1
  • 8
  • 25