Summary:
We know migration is the process of shifting our database schema to another more efficient one that enables you to meet the changing trends and update with the latest technologies. Rails Migrations is an ever-known concept that allows you to change your application’s database schema. With its increasing popularity within the tech development marketplace, in this blog post, we will delve into the various facets of the Rails Migration, its need, and other factors that must be considered when performing a Rails migration.
When considering the Rails Migrations, it is crucial to understand that change is of the essence. Migrations are the ways that allow you to alter or modify your database schema within your Rails application that too in a consistent and organized manner. It allows you to use Ruby code instead of SQL, which offers several advantages.
In place of managing the SQL scripts, it requires you to define the database changes within the DSL. The code here is database-independent, allowing you to move your application to an entirely new platform quickly. You can edit the SQL fragments, update your team about the changes made and, after that, run them. Also, tracking the changes that must be run against the production machines the next time you deploy your application is crucial.
In simple words, migration can be referred to as the new database version. Every migration alters the database by adding and removing tables, columns, or entries. The Active record with this is responsible for updating the db/schema.rb file for matching it to the up-to-date structure of your database.
Rails Migrations is a powerful feature of the Ruby on Rails framework that infers its importance for database management and application development. Below given are a few of the migration Rails features that can help you build more robust and maintainable applications:
Migration Rails presents to you the option to add, remove, and modify tables, columns, and various other database objects in a format that is reversible as per requirements. This allows for data integrity and makes it easy to roll back changes as necessary.
Being written in Ruby and not SQL, Migrations can be used with any database that Active Record supports. This feature lets you quickly move your application from one database to a different database platform if needed.
You can track the migrations in your applications’ source code repository, along with other code files, thus, making it easier to the changes that have been made to your database over time and roll back to a previous version if needed.
The Rails migration generator offers simple ways to create and update new migrations. You can use the command rake db:migrate to apply the pending migrations within your database.
Migration in Rails can be an effective way to efficiently manage your database schema in a simple yet efficient manner. Thus, they are a crucial part of the Rails application. Some other add-on benefits of Rails Migrations are:
To configure your Rails Migration, you must set up your application for creating and managing the database schema changes using the Rails framework. Below is a step-by-step guide that will help you move ahead with the Rails Migration configuration and use it.
The first step is to create a new Rails application using the command ‘rails new.’
Open your terminal and navigate to your Rails app directory using the ‘cd’ command.
Using the ‘rails generate migration’ command, create a new migration.
Example:
For creating migration for the addition of a new table called “bacancyproduct,” you can run the command below:
The command given above will generate a new migration file in the ‘db/migrate’ directory with a name such as ‘20230809101030_create_bacancyproducts.rb’; with this, the timestamp given illustrates the current date and time.
Open your generated new migration file in a Rails text editor. Now, define the changes you must make to the database schema.
Example:
You can easily add columns to a table, create new tables, add indexes, and define constraints.
class CreateBacancyproducts < ActiveRecord::Migration[6.0] def change create_table :bacancyproducts do |t| t.string :name t.decimal :price t.timestamps end end end
To apply the changes defined within the migration, run the command ‘rails db:migrate’ in your terminal as shown below:
The above command will execute the migration and update the database schema accordingly.
Rolling back migration in Rails is, as the name suggests, a way to undo a change already made to your database using a migration. It is highly effective when you need to revert a change in case you find errors in the system while running a migration.
It is an optional step in case you need it for convenience. As rolling back or deleting a migration requires you to be careful as it may lead to unintended consequences on your database and can even sometimes crash the system.
To perform rollback migration, use the ‘rails db:rollback’ command to undo the last migration applied.
It is the step that enables you to get the status of your migrations and the ones that have been applied; use the ‘rails db:migrate:status’ command in your terminal as given below:
Rails Migrations present vast options and configurations you can use based on your specific requirements.
Example:
Use can use data types, add index, define foreign key constraints, and more. You can also use the migration generators to create specific migrations efficiently and effectively.
Migrations are an integral part of your Rails application development lifecycle. The offer manages database schema changes in a controlled and organized manner, making it more straightforward and more effective to collaborate with other developers and maintain the data integrity as the app evolves.
Scale Up your Application’s Efficiency with Ruby on Rails
Our best-in-class Ruby on Rails Upgrade services ensure a simple yet effective upgradation to your existing Rails application with next-gen features and breath-taking experiences for your end-users.
In the above segment, we glimpsed at the step to configure and use migration in Rails. Let us use the code examples for creating and applying specific Rails Migrations within your application system.
Initially, create the new migration file by running the command given below:
The above command creates a new migration file called add_column_to_users.rb in the db/migrate directory.
Open the add_column_to_users.rb file and add the following code:
class AddColumnToUsers < ActiveRecord::Migration[6.1] def up add_column :users, :name, :string end def down remove_column :users, :name end end
Then, Run the rake db:migrate command to apply the migration to your database. This will add the name column to the users table in your database.
Now, moving ahead, let us look at the steps to create a rails migrate for the below-given tasks:
? Add a Column
For adding a new column to a model, use the add_column method.
Example:
The said migration would add an age column to the users table:
class AddAgeToUsers < ActiveRecord::Migration[6.1] def up add_column :users, :age, :integer end def down remove_column :users, :age end end
? Change a Column
For changing the type of a column, use the change_column method.
Example:
The following migration changes the type of the name column from string to text:
class ChangeNameColumnToText < ActiveRecord::Migration[6.1] def up change_column :users, :name, :text end def down change_column :users, :name, :string end end
? Add a New Model (or Table)
For adding a new model (or table), you would use the create_table method.
Example:
The following migration would create a new table called posts:
class CreatePosts < ActiveRecord::Migration[6.1] def up create_table :posts do |t| t.string :title t.text :body t.timestamps end end def down drop_table :posts end end
? Execute SQL
To execute SQL directly, use the execute method.
Example:
The following migration would execute the SQL statement ALTER TABLE users ADD COLUMN age INT;
class AddAgeToUsers < ActiveRecord::Migration[6.1] def up execute("ALTER TABLE users ADD COLUMN age INT;") end def down execute("ALTER TABLE users DROP COLUMN age;") end end
When performing the migration in rails, a few factors play a crucial role in ensuring that your rails migration is effective without much hassle. Below are a few such tips that will help you better understand how you can prevent any Ruby on Rails migration errors:
As we have discussed before, rollback migration is a simple way by which you can easily undo the final edit you have made within the system by using the rails db:rollback command, and after that, complete the migration by resolving the issue and making the final edits.
Irreversible MIgrations are the ones that prevent anybody working on the migration in Rails from rolling back the changes made.
Simply put, these are the exception that can be raised to stop the migration from being rolled back. You must avoid using irreversible migrations, as mitigating this issue is tedious.
When running the migrations on the new database is complex, the best choice is to clean up the old ones because poorly written migrations cause such failures. Cleaning at this moment means deleting the files from the db/migrations folder.
Migration in Rails is ideal for only the schema changes and not for the existing data. Therefore, you should create temporary rake tasks for complex data migrations. This is how we can keep the deployment separate from the data changes.
Rails Migrations is the ideal way by which you can effectively change your database schema. This makes it possible to use a version control system and synchronize things with the actual code. However, doing it the right way is of the essence to leverage its true potential. If you are also a business owner and planning for Rails Migrations in 2023, then it is crucial to have experts onboard. Hire Ruby on Rails developer from Bacancy and make your Ruby on Rails migration smoother than ever.
Migrations are a feature of the Active Record that enables you to evolve your database schema over time. They enable you to use the Ruby DSL for illustrating changes to your table instead of obligating you to write schema modifications in pure SQL.
Generally, Rails uses only the migration number (the timestamp) for tracking and identifying the migrations. Initially, the migration started at 1, which was increased every time another migration was made; this needed rolling back the whole migration and renaming it to prevent clashes. But, after Rails 2.1, it was avoided as it involved using the creation time of migration for identification.
Migrating Rails mainly brings three advantages: enhanced efficiency, better data security, and increased data quality.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.