0
0
Ruby on Railsframework~5 mins

Changing column types in Ruby on Rails

Choose your learning style9 modes available
Introduction

Changing column types lets you update how data is stored in your database. This helps keep your app's data accurate and useful.

You want to store numbers instead of text in a column.
You need to change a date column to a datetime for more detail.
You want to switch a column from integer to string to hold letters.
You realize a column's current type doesn't fit the data you want to save.
Syntax
Ruby on Rails
change_column :table_name, :column_name, :new_type
Use this inside a Rails migration file.
You can add options like :limit or :default after the type.
Examples
This changes the 'age' column in 'users' table from its current type to string.
Ruby on Rails
change_column :users, :age, :string
This changes 'price' to a decimal with 8 digits total and 2 after the decimal point.
Ruby on Rails
change_column :orders, :price, :decimal, precision: 8, scale: 2
This updates 'start_time' to store both date and time.
Ruby on Rails
change_column :events, :start_time, :datetime
Sample Program

This migration changes the 'age' column in the 'users' table from its current type to a string type. Run this migration to update the database schema.

Ruby on Rails
class ChangeAgeTypeInUsers < ActiveRecord::Migration[7.0]
  def change
    change_column :users, :age, :string
  end
end
OutputSuccess
Important Notes

Changing column types can cause data loss if the new type can't hold old data properly.

Always back up your database before running migrations that change column types.

Test your app after changing column types to make sure everything works well.

Summary

Use change_column in migrations to update a column's data type.

Be careful of data loss and test after changes.

Adding options like precision or scale helps define numeric columns better.