Rails set default DateTime to now

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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



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