If I'm adding a column via MySQL, I can specify where in the table that column will be using the AFTER modifier. But if I do the add_column via a Rails migration, the column will be created at the end of the table.
Is there any functionality for rails migrations to specify the position of an added column?
To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users.
When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.
Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.
This is now possible in Rails 2.3.6+ by passing the :after parameter
https://rails.lighthouseapp.com/projects/8994/tickets/3286-patch-add-support-for-mysql-column-positioning-to-migrations
To everyone that doesn't see the advantage in having this feature: do you never look at your database outside of the ORM? If I'm viewing in any sort of UI, I like having things like foreign keys, status columns, flags, etc, all grouped together. This doesn't impact the application, but definitely speeds up my ability to review data.
Sure you can.
Short answer:
add_column :users, :gender, :string, :after => :column_name
Long answer:
Here is an example, let's say you want to add a column called "gender" after column "username" to "users" table.
rails g migration AddGenderToUser gender:string
Add "after => :username" in migration that was created so it looks like this:
class AddSlugToDictionary < ActiveRecord::Migration
def change
add_column :users, :gender, :string, :after => :username
end
end
I created a patch that adds this additional functionality to the ActiveRecord Mysql adapter. It works for master and 2-3-stable.
https://rails.lighthouseapp.com/projects/8994/tickets/3286-patch-add-support-for-mysql-column-positioning-to-migrations
It might be mysql specific, but it doesn't make your migrations any less portable (other adapters would just ignore the extra positioning options).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With