January 7, 2023 By Matthew Rathbone *
On this page

A big integer is a data type that can hold a larger range of values than a regular integer. In most programming languages, including Ruby, an integer is a whole number that can be positive, negative, or zero. It is stored in a fixed number of bits, typically 32 or 64. This means that the maximum value an integer can hold is limited by the number of bits it uses to store the value.

A big integer, on the other hand, can hold much larger values because it uses a variable number of bits to store the value. This makes it suitable for storing large numbers, such as those used in financial applications or scientific calculations.

To change an integer column to a big integer column in a Rails application, you can use a migration. Migrations are written in Ruby and are stored in the db/migrate directory of a Rails project. To create a new migration, you can use the rails generate migration command followed by the name of the migration and any additional arguments.

For example, to create a migration to change the price column in the products table from an integer to a big integer, you might run the following command:

rails generate migration change_price_to_bigint

This will create a new migration file in the db/migrate directory with a timestamp as part of the file name. The file will contain a class with a change method that you can use to make changes to the database.

To change the price column to a big integer, you can use the change_column method and pass it the name of the table, the name of the column, and the new data type. The change_column method will automatically create a new big integer column and copy the data from the old integer column to the new one. It will also remove the old column.

Here’s an example of how you might use the change_column method in the change method of your migration:

class ChangePriceToBigint < ActiveRecord::Migration[6.0]
  def change
    change_column :products, :price, :bigint
  end
end

Once you’ve written your migration, you can run it using the rails db:migrate command. This will execute the change method of your migration and make the specified changes to the database.

Migrations are an important tool for managing changes to a database in a Rails application. They allow you to make changes to the structure of your database in a safe and reversible way, which is especially important when working on a team or deploying your application to a production environment. By using a migration to change an integer column to a big integer column, you can ensure that your application can store larger numbers without encountering any errors or limitations.