Migrate default now()


#1

I want to set default value to current time of database:

class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
# …
t.column :created_at, :timestamp, :null => false, :default =>
‘now’
end
end
#…
end

On postgresql, it is converted to:
created_at timestamp NOT NULL DEFAULT ‘2006-04-25
11:34:45.725837’::timestamp without time zone

Modify to:
t.column :created_at, :timestamp, :null => false, :default =>
‘current_timestamp’

It is converted to:
created_at timestamp NOT NULL DEFAULT ‘current_timestamp’
It’s wrong.

I try to fixed it:
default_fix.rb:
module ActiveRecord
module ConnectionAdapters # :nodoc:
module SchemaStatements
def add_column_options!(sql, options) #:nodoc:
unless options[:default].nil?
if options[:default] == “now”
sql << " DEFAULT #{now(options[:default],
options[:column])}"
else
sql << " DEFAULT #{quote(options[:default],
options[:column])}" unless options[:default].nil?
end
end
sql << " NOT NULL" if options[:null] == false
end
end
end
end

module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def now(value, column)
“current_timestamp”
end
end
end
end

test code:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
# …
t.column :created_at, :timestamp, :null => false, :default =>
‘now’
end
end
#…
end

It works find. but is this way correct?