可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
When I run rake db:migrate I get an error. Is my syntax wrong or am I missing something else?
回答1:
Yes, you are missing the type :
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
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.
回答2:
If you want postgres to set default time on inserts, you need
`default: "now()"`
The only way we found to achive this was to do a migration on an existing datetime column, like this:
#migration execute("ALTER TABLE teams ALTER COLUMN wk1_time SET DEFAULT CURRENT_TIMESTAMP")
that produces a schema.rb entry shown like this:
#schema.rb t.datetime "wk1_time", default: "now()", null: false
回答3:
You're going to run into problems settings the default date time in the migration. This is because DateTime.now
will be evaluated based upon when the migrate runs, not when the record is created!
To fix that you'll need to create an ActiveRecord callback in order to set wk1_time
like so:
before_create :set_default_wk1_datetime def set_default_wk1_datetime self.wk1_time = DateTime.now end
回答4:
for Postgresql :
add_column :users, :msgs_seen_at, 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'
but you'll have to use user.reload
after user = User.create
in order to "see" msgs_seen_at