Take the 2-minute tour ×

Consider the table creation script below:

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

Is it's possible to set the default value as the current time?

I am trying to find a DB independent equivalent in rails for the SQL column definitions given below:

Oracle Syntax


MySQL Syntax



share|improve this question
add comment

3 Answers

up vote 48 down vote accepted

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

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

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.

share|improve this answer
Currently I am setting the value in the :before_create callback.<br> I was looking for some type of AR magic here. I spent some time looking at the Rails code, but I didn't find any solution. I thought I will ask around to see if there are any alternatives. –  Harish Shetty Oct 17 '09 at 0:00
I would suggest doing it with a callback on before_create. –  jonnii Oct 17 '09 at 0:01
I don't want to alter the DB table as I want to keep my code DB neutral. I was hoping that AR had some mechanism to set the default value for the Datetime field similar to created_at field. –  Harish Shetty Oct 17 '09 at 0:09
Be careful with Time.now. Usually you want to use Time.zone.now. –  Jeewes Feb 19 at 19:01
add comment

If you have a datetime column called created_at or created_on, ActiveRecord will 'magically' set it to the creation datetime. You don't need to do anything else except to have that column.

You can also have updated_at or updated_on and it will get updated when a record is updated.

share|improve this answer
I already have those fields in my table. I need an additional field for my scheduler to hold the start date. Currently, I am using :before_create callback to set the current date. If I encounter this scenario frequently, I have to resort to writing a plugin to alter the default value handling in 'to_sql' method of ColumnDefinition class. –  Harish Shetty Oct 17 '09 at 7:45
add comment

I was searching for a similar solutions but I ended using https://github.com/FooBarWidget/default_value_for.


class User < ActiveRecord::Base
  default_value_for :name, "(no name)"
  default_value_for :last_seen do

u = User.new
u.name       # => "(no name)"
share|improve this answer
add comment

Your Answer


