Various rails migration operations

What to do in this article

--How to add / remove constraints to columns with NOT NULL constraints --How to delete index from column linked with multiple columns --How to delete a column with a foreign key created with reference type

Add / remove NOT NULL constraint

When you want to add a NOT NULL constraint

def up
  change_column_null :posts, :content, false
end

def down
  change_column_null :posts, :content, true
end

The point is to use the up / down method instead of the change method.

When you want to remove a NOT NULL constraint

def up
  change_column_null :posts, :content, true
end

def down
  change_column_null :posts, :content, false
end

Remove index from column with composite key index

def change
  remove_index :likes, column: [:user_id, :post_id], unique: true
end

When deleting the index from a single column, do as follows

def change
  remove_index :likes, column: :micropost_id, unique: true
end

How to delete a column with a foreign key created with reference type

def change
  remove_reference :posts, :user, null: false, foreign_key: true
end

foreign_key: If you have set a foreign key with true, you should add it as well.

bonus

Check if a column has an index (in MySQL)

mysql > SHOW CREATE TABLE tbl_name

reference

https://dev.mysql.com/doc/refman/5.6/ja/show-create-table.html

https://railsguides.jp/active_record_migrations.html

https://qiita.com/akinov/items/852fe789fe98a44350a9

Recommended Posts

Various rails migration operations
Master various migration operations
Rails migration
[Rails] About migration files
[Rails] Migration command summary
Understand migration in rails
Various Ruby string operations
[rails] Deleted NOFILE migration file
Cancel Ruby on Rails migration
rails console Frequently used operations
[Rails] Delete the migration file
[Rails] Various ways to delete data
Check the migration status of rails
Migration file to add comment to Rails table
Rails migration column changes and so on.