【发布时间】:2011-07-08 15:56:13
【问题描述】:
我需要将我正在制作的应用的列类型从日期更改为日期时间。我不关心数据,因为它仍在开发中。
我该怎么做?
【问题讨论】:
标签: mysql ruby-on-rails ruby ruby-on-rails-3 migration
我需要将我正在制作的应用的列类型从日期更改为日期时间。我不关心数据,因为它仍在开发中。
我该怎么做?
【问题讨论】:
标签: mysql ruby-on-rails ruby ruby-on-rails-3 migration
首先在您的终端中:
rails g migration change_date_format_in_my_table
然后在你的迁移文件中:
对于 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
【讨论】:
change 方法来代替 up 和 down 方法,那是因为 the change method doesn't support the change_column migration definition。
此外,如果您使用的是 Rails 3 或更新版本,则不必使用 up 和 down 方法。你可以使用change:
class ChangeFormatInMyTable < ActiveRecord::Migration
def change
change_column :my_table, :my_column, :my_new_type
end
end
【讨论】:
This migration uses change_column, which is not automatically reversible.To make the migration reversible you can either:1. Define #up and #down methods in place of the #change method.2. Use the #reversible method to define reversible behavior.
在 Rails 3.2 和 Rails 4 中,Benjamin 的 popular answer 语法略有不同。
首先在您的终端中:
$ rails g migration change_date_format_in_my_table
然后在你的迁移文件中:
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
【讨论】:
有一个change_column 方法,只需在迁移中执行它,将 datetime 作为新类型即可。
change_column(:my_table, :my_column, :my_new_type)
【讨论】:
AFAIK,迁移是为了在进行架构更改时尝试重塑您关心的数据(即生产)。因此,除非那是错误的,并且既然他确实说过他不关心数据,为什么不直接从日期到日期时间修改原始迁移中的列类型并重新运行迁移呢? (希望你有测试:))。
【讨论】:
rake db:migrate:reset 的用途。