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

柔情痞子 提交于 2019-12-04 16:56:10

问题


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


回答1:


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.




回答2:


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.




回答3:


Delete and regenerate db\schema.rb file.

rake db:schema:dump



回答4:


A hack, but it should get you where you need to go:

class ChangePrecisionAndScaleOfPaybackPeriodInTags < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE tags CHANGE payback_period DECIMAL(3,10)"
  end

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


来源:https://stackoverflow.com/questions/2450494/rails-cannot-add-precision-or-scale-options-with-change-column-in-a-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!