How to set a default value for a datetime column to record creation time in a migration?

后端 未结 7 689
日久生厌
日久生厌 2020-12-04 13:42

Consider the table creation script below:

create_table :foo do |t|
  t.datetime :starts_at, :null => false
end

Is it\'s possible to set

7条回答
  •  隐瞒了意图╮
    2020-12-04 14:20

    You can add a function in a model like this:

      before_create :set_foo_to_now
      def set_foo_to_now
        self.foo = Time.now
      end
    

    So that the model will set the current time in the model.

    You can also place some sql code in the migration for setting the default value at the database level, something like:

    execute 'alter table foo alter column starts_at set default now()'
    

    Setting something like this:

    create_table :foo do |t|
      t.datetime :starts_at, :null => false, :default => Time.now
    end
    

    causes executing the Time.now function during migrating so then the table in database is created like this:

    create table foo ( starts_at timestamp not null default '2009-01-01 00:00:00');
    

    but I think that it is not what you want.

提交回复
热议问题