Rails Cheat Sheet to create migration
This blog will be a lifesaver for some. I am going to share with you the shortcut to create models, tables and migrations in rails using the active record migrations.
Create a new table
rails g model Restaurant name:string
This results in the following migrations
class CreateRestaurants < ActiveRecord::Migration
def change
create_table :restaurants do |t|
t.string :name
t. timestamps null: false
end
end
end
If you want to generate table with more columns you could just put the name of the column and the data type next to each other. For example
rails g model Restaurant name:string count:integer supplier:references
Will result in the following migrations
rails g model Restaurant name:string
This results in the following migrations
class CreateRestaurants < ActiveRecord::Migration
def change
create_table :restaurants do |t|
t.string :name
t.integer :count
t.references :supplier, index: true, foreign_key: true
t. timestamps null: false
end
end
end
Add a column
Lets say we want to add a column locations of type string to our restaurant model
rails g migration AddLocationsToRestaurant locations: string
The resulting migrations would be
class AddLocationsToRestaurant < ActiveRecord: Migration
def change
add_column :restaurants, :locations, :string
end
end
You can also add foreign key with this method. For example we want to add a foreign key Waiter, we can apply the same method, replacing name and type
rails g migration AddWaiterToRestaurant waiter:references
Remove a Column
To remove the locations column we just added
rails g migration RemoveLocationsFromRestaurant locations
Results in
class RemoveLocationsFromRestaurant < ActiveRecord::Migration
def change
remove_column :restaurants, :locations, :string
end
end
Rename a Column
Let’s say we want to rename our location column to rating
rails g migration RenameRestaurantLocationToRating
Manually add the rename_column to the resulting migrations
class RenameRestaurantLocationToRating < ActiveRecord::Migration
def change
rename_column :restaurants, :location, :rating
end
end
Running Migrations
rake db:migrate
In production:
rake db:migrate RAILS_ENV=”production”
I hope that this is helpful. For more migrations check out the official active record migrations link provided in the References
References
https://guides.rubyonrails.org/active_record_migrations.html