Rails migration generator - how to specify decimal precision and scale


I always forget how to specify decimal scale and precision when using the migration generator.

The right way to do it is:

rails g migration add_bodyweight_to_workouts bodyweight:decimal{5,2}

But this does not work if you are using zsh and instead you get the following migration:

class AddBodyweightToWorkouts < ActiveRecord::Migration
  def change
    add_column :workouts, :bodyweight, :decimal5
    add_column :workouts, :bodyweight, :decimal2
  end
end

You obviously didn’t want this. In order to get what you wanted, you can either replace the comma with a hyphen or quote the field declaration:

rails g migration add_bodyweight_to_workouts bodyweight:decimal{5-2}
rails g migration add_bodyweight_to_workouts 'bodyweight:decimal{5,2}'

Both of them result in the following migration:

class AddBodyweightToWorkouts < ActiveRecord::Migration
  def change
    add_column :workouts, :bodyweight, :decimal, precision: 5, scale: 2
  end
end

Much better! Let’s just hope that no people exist that weigh more than 999 pounds…

Related Posts

The Safe Navigation Operator (&.) in Ruby

Ruby 2.3 introduces the &. operator which will make dealing with nils easier

Benchmarking Ruby

How to benchmark ruby code and compare different solutions to a problem

The Null Object pattern

Hi, World

Every techie's first post