jacoulter
jacoulter

Reputation: 740

Rails Migration Decimal Column :default=> 0 re-setting MySQL precision to 0?

I'm using Rails 3.0.3 (don't ask) and when I run a migration for table with decimal column and set :default => 0 it's re-setting the column's scale and precision to (10,0).

def self.up
 create_table :courses do |t|
  t.integer :user_id
  t.string :name
  t.decimal :distance, :precision => 5, :scale => 2, :default => 0
  t.text :notes

  t.timestamps
 end
end

When I remove the :default=>0 option from the migration the column's scaled and precision are correct: (5,2)

I tried running a change_column migration with only :default =>: 0 set, but the column's scale and precision were re-set to (10,0)

change_column :courses, :distance, :decimal, :default => 0.0

I know I can go into MySQL and correct the precision and scale of the column, but wondering if I'm doing something wrong or if this is a bug?

Google reveals no information so I think I'm doing something wrong.

Upvotes: 6

Views: 8984

Answers (4)

fabOnReact
fabOnReact

Reputation: 5942

I am just trying this right now and seems to work.

Active Records Migrations

class ChangeVisitratioFormatInCampaigns < ActiveRecord::Migration[5.0]
  def change
    reversible do |dir|
        change_table :campaigns do |t|
            dir.up { t.change :visitratio, :decimal, :precision => 5, :scale => 4, :default => 1 }
            dir.down { t.change :visitratio, :integer }
        end
    end
  end
end

Upvotes: 0

ılǝ
ılǝ

Reputation: 3528

You can also do

def change
    change_column :courses , :distance, :decimal, :precision => 5, :scale => 2, :null => false, :default => '0'
end

Upvotes: 1

hers19
hers19

Reputation: 146

Try this one: t.decimal :distance, :precision => 5, :scale => 2, :default => 0.00

Upvotes: 6

Hishalv
Hishalv

Reputation: 3052

I was also stuck on this one, and i cant find a solution to it. Eventually i had to go into mysql and change the required precision, scale and default value, i used this from here with a few modifications

mysql> ALTER TABLE question ADD (price INTEGER);
mysql> ALTER TABLE question DROP price;
mysql> ALTER TABLE question ADD (frig DECIMAL(5,2));
mysql> ALTER TABLE question CHANGE frig price DECIMAL(5,2);
mysql> ALTER TABLE question ALTER status SET DEFAULT '0';
mysql> ALTER TABLE question MODIFY price INTEGER;

Also try :default => 0.0 #note the 0.0 as the default value must be in the data type specified i.e. decimal

Hope it helps.

Upvotes: 2

Related Questions