MySQL 在 ROR 迁移期间将列类型从 Date 更改为 DateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5191405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change a column type from Date to DateTime during ROR migration
提问by jdog
I need to change my column type from date to datetime for an app I am making. I don't care about the data as its still being developed.
我需要将我正在制作的应用程序的列类型从日期更改为日期时间。我不在乎数据,因为它仍在开发中。
How can I do this?
我怎样才能做到这一点?
回答by apneadiving
First in your terminal:
首先在您的终端中:
rails g migration change_date_format_in_my_table
Then in your migration file:
然后在您的迁移文件中:
For Rails >= 3.2:
对于 Rails >= 3.2:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
回答by Lee McAlilly
Also, if you're using Rails 3 or newer you don't have to use the up
and down
methods. You can just use change
:
此外,如果您使用的是 Rails 3 或更新版本,则不必使用up
anddown
方法。你可以只使用change
:
class ChangeFormatInMyTable < ActiveRecord::Migration
def change
change_column :my_table, :my_column, :my_new_type
end
end
回答by Thomas Klemm
In Rails 3.2 and Rails 4, Benjamin's popular answerhas a slightly different syntax.
在 Rails 3.2 和 Rails 4 中,Benjamin 的流行答案的语法略有不同。
First in your terminal:
首先在您的终端中:
$ rails g migration change_date_format_in_my_table
Then in your migration file:
然后在您的迁移文件中:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
回答by Nikita Rybak
There's a change_columnmethod, just execute it in your migration with datetime as a new type.
有一个change_column方法,只需在迁移中使用 datetime 作为新类型执行它。
change_column(:my_table, :my_column, :my_new_type)
回答by fakeleft
AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).
AFAIK,迁移是为了在进行架构更改时尝试重塑您关心的数据(即生产)。因此,除非那是错误的,并且既然他确实说过他不关心数据,那么为什么不直接将原始迁移中的列类型从 date 修改为 datetime 并重新运行迁移呢?(希望你有测试:))。