Rails 将默认日期时间设置为现在 [英] Rails set default DateTime to now
问题描述
在我的应用中,我有团队,每个团队每周都有一次比赛时间.我希望将游戏时间设置为现在"作为默认值.我的桌子是这样设置的
In my app I have teams and each team has a game time every week. I want the game times to be set to 'now' as a default. My table is set up like so
create_table "teams", force: true do |t|
t.datetime "wk1_time"
end
我创建了一个迁移,它看起来像这样:
I created a migration and it looks like this:
class ChangeDateTimeDefault < ActiveRecord::Migration
def change
change_column :teams, :wk1_time, :default => DateTime.now
end
edn
当我运行 rake db:migrate 时出现错误.是我的语法错误还是我遗漏了其他东西?
When I run rake db:migrate I get an error. Is my syntax wrong or am I missing something else?
推荐答案
是的,您缺少类型:
class ChangeDateTimeDefault < ActiveRecord::Migration
def change
change_column :teams, :wk1_time, :datetime, :default => DateTime.now
end
end
但是,您需要下面的而不是上面的,因为您只想更改默认.
But, you need the below not the above one, because you just want to change the default.
class ChangeDateTimeDefault < ActiveRecord::Migration
def change
change_column_default :teams, :wk1_time, DateTime.now
end
end
但这些都不是您任务的正确方法.原因是 DateTime.now
将根据您运行迁移的时间而不是创建记录的时间进行评估.您需要查看此答案以了解如何设置默认时间.
But none of these are correct approach for your task. The reason is DateTime.now
will be evaluated based upon when you ran the migration, instead when the record is created. You need look to into this answer to know how to set the default time.
这篇关于Rails 将默认日期时间设置为现在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!