Rails set default DateTime to now

前端 未结 5 1073
Happy的楠姐
Happy的楠姐 2021-01-06 00:42

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_         


        
5条回答
  •  有刺的猬
    2021-01-06 01:08

    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
    

提交回复
热议问题