Add and Change Default Column Value in Ruby on Rails

In Ruby on Rails, it's easy to set and change a default value for columns in your application database. Say we have an online shop, and we want to set a default price for our products. How can we do that? And if we want to change the default price later, how do we do that? In this post, we'll talk about how we can achieve that in Ruby on Rails. We'll use Ruby on Rails 7.0.2.3 and Ruby 3.1.2.

Let's start by creating a new application. Let's call it my_shop. From your terminal type:

rails new my_shop

Let's change the directory to the application folder:

cd my_shop

Let's generate a Product scaffold. The product has three attributes: title, description, and price. 

bin/rails g scaffold Product title:string description:text price:float

We must edit this migration to set the default price. Let's go to db/migrate/ folder and open our file and edit it like this:

class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :products do |t|
      t.string :title
      t.text :description
      t.float :price, default: 10.00
      t.timestamps
    end
  end
end

We can run now this migration in the terminal:

bin/rails db:migrate

Let's set the root route to the products index action. In config/routes.rb add this at the top of the Rails.application.routes.draw do block:

root 'products#index'

All the products you'll add to your database will have a default price of 10.0. But what if, in the future, you'll have to raise the price? In Rails, it's easy to write a migration to change the default value of  a column. First, let's generate a migration file:

bin/rails g migration ChangeDefaultPriceOfProducts

Let's open this migration file and edit it. Here, we'll use the Rails method change_column_default. Here is how our migration looks after we edit it:

class ChangeDefaultPriceOfProducts < ActiveRecord::Migration[7.0]
  def change
   change_column_default :products, :price, 11.0
  end
end

 Let's run this migration:

bin/rails db:migrate

Then we restart the server, and from now on, all the products we add to the database will have this default price of 11.0.

Post last updated on Sep 11, 2022