views:

487

answers:

2

Consider the table creation script below:

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

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

start_at DATE DEFAULT SYSDATE()

MySQL Syntax

start_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

OR

start_at DATETIME DEFAULT NOW()
+1  A: 

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.

Simon
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.
KandadaBoggu
I would suggest doing it with a callback on before_create.
jonnii
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.
KandadaBoggu
+1  A: 

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.

Jim
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.
KandadaBoggu