Rails set default DateTime to now

前端 未结 5 1083
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 00:58

    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

    0 讨论(0)
  • 2021-01-06 01:02

    Since Rails 5 you can make a migration like this:

    change_column_default :users, :wk1_time, -> { 'CURRENT_TIMESTAMP' }
    

    In my mind this is the best option because it not database specific answer.

    0 讨论(0)
  • 2021-01-06 01:06

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-06 01:16

    The way I found, 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
    

    The "now()" is a string sent to postgresql and evaluated at runtime, upon each insert

    0 讨论(0)
提交回复
热议问题