Tuesday, January 19, 2016

Rails 4 Migrations


http://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4

When you already have a users and uploads table and wish to add new relationship between them.

All you need to do is, just generate a migration using following command:rails g migration AddUserToUploads user:references

which will create a migration file as:

class AddUserToUploads < ActiveRecord::Migration
  def change 
    add_reference :uploads, :user, index: true 
  end 
end

Then run the migration using rake db:migrate. This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table) PLUS it will also add an index on the new column.


To change the data type of a column:

http://www.devkit.co/code/17-rails-edit-column-type/

class ChangeColumnType < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

No comments:

Post a Comment