Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Cannot add :precision or :scale options with change_column in a migration?

This seems to have been asked before: rails decimal precision and scale

But when running a change_column migration for :precision or :scale they don't actually affect the schema or database, but db:migrate runs without errors.

My migration file looks like this:

class ChangePrecisionAndScaleOfPaybackPeriodInTags < ActiveRecord::Migration
  def self.up
    change_column :tags, :payback_period, :decimal, { :scale => 3, :precision => 10 }
  end

  def self.down
    change_column :tags, :payback_period, :decimal
  end
end

But my schema (and the data) remains as:

t.decimal  "payback_period"

Anybody else have this issue?

Thanks,

Josh

like image 483
Joshua Pinter Avatar asked Mar 15 '10 21:03

Joshua Pinter


People also ask

What is precision and scale in Rails?

For clarity's sake: the precision is the number of significant digits, while the scale is the number of digits that can be stored following the decimal point. For example, the number 123.45 has a precision of 5 and a scale of 2. A decimal with a precision of 5 and a scale of 2 can range from -999.99 to 999.99.

What is activerecord migration?

Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use a Ruby DSL to describe changes to your tables.

How to run migration in Rails?

Active Record tracks which migrations have already been run so all you have to do is update your source and run rake db:migrate. Active Record will work out which migrations should be run. It will also update your db/schema. rb file to match the structure of your database.


3 Answers

Had a related (but not same) problem. I was just changing scale, so when changing the :scale you need the full line:

change_column :something, :weight, :decimal, :precision => 10, :scale => 2

omitting :decimal (which it already was) and :precision (which already was 10) will cause the migration to fail.

like image 101
rtfminc Avatar answered Oct 17 '22 18:10

rtfminc


Does Not Work for SQLite3

For this simple test app that I'm running I have SQLite3 setup. Apparently, SQLite3 doesn't rely on column type declarations and is more dynamic, looking at the column's content instead - as was stumbled upon here:

Modify a Column's Type in sqlite3

I haven't tested it but I'm sure that's why the schema wasn't being changed, because change_column doesn't translate to anything in SQLite3.

Thanks for the replies guys.

like image 38
Joshua Pinter Avatar answered Oct 17 '22 17:10

Joshua Pinter


Delete and regenerate db\schema.rb file.

rake db:schema:dump
like image 1
Harish Shetty Avatar answered Oct 17 '22 16:10

Harish Shetty