Migrations in Rails
Active records provide us with a very useful feature to change or alter our database schema in ruby on rails.
Through these migrations we can make necessary changes to our database and make changes in our tables and rows.
Active records detects the changes we have made and automatically update the database.
The command to tell active records to update the changes in the schema is
rake db:migrate
Migrations which we can use to alter our schema are as fallows :
To create a table we will have to write this command in console
$ rails generate model user name:string email:string
and then run
$ rake db:migrate
Now, the migration file will look like this
class ChangeUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
- Adding a column to an existing table
To add a column to an existing table we need to write this command in console
$ rails generate migration add_column_address_to_users address:text
and then run
$ rake db:migrate
Now, the migration file will look like this
class AddColumnAddressToUser < ActiveRecord::Migration
def change
add_column :users, :address, :text
end
end
With this, an address column with data type text will be added to the user table.
- Adding an index to the added column
To add an index to the added column we need to write this command in console
$ rails generate migration add_column_address_to_users address:text:index
and then run
$ rake db:migrate
Now, the migration file will look like this
class AddColumnAddressToUser < ActiveRecord::Migration
def change
add_column :users, :address, :text
add_index :users, :address
end
end
- Removing a column from table
To remove a column from an existing table we need to write this command in console
$ rails generate migration remove_column_address_from_users address:text
and then run
$ rake db:migrate
Now, the migration file will look like this
class AddColumnAddressToUser < ActiveRecord::Migration
def change
remove_column :users, :address, :text
end
end
To add a reference to a table of some another table we need to write this command in console
$ rails generate migration add_refrence_user_to_guests
and then run
$ rake db:migrate
Now, the migration file will look like this
class AddUserRefToGuests < ActiveRecord::Migration
def change
add_reference :guests, :user, index: true
end
end
In this the user table is added as a reference to the guests table.
This migration will create a user_id
column and appropriate index in the guests table.
So these were some of the important migrations of active records which are used frequently while creating we b based applications.
0 Comment(s)