I’ve been using the migration system in Ruby - and I recently added some of the Magic Field Names
class TimeStamp < ActiveRecord::Migration
def tables
[:my_table,:my_other_table,:my_other_other_table]
end
def self.up
#This change turns on optimstic locking for all of the important tables
for table in tables
add_column table, :created_at, :timestamp , :null => true, :default => “now()”
add_column table, :updated_at, :timestamp , :null => true, :default => “now()”
forbid_null table, :created_at, “now()”
forbid_null table, :updated_at,”now()”
end
end
def self.down
for table in tables
remove_column table , :created_at
remove_column table , :updated_at
end
end
def forbid_null(table,column, default = nil)
if !default.nil?
conditions = [" #{column} = ? ", default]
sql = ActiveRecord::Base.send(:sanitize_sql,conditions)
puts “UPDATE #{table} SET #{sql}”
execute “UPDATE #{table} SET #{sql}”
end
execute “ALTER TABLE #{table} ALTER #{column} SET NOT NULL;”
end
end
Ok I’ve hit a small problem with the above code. You see the Rails system is using sanitize_sql to make sure that nothing bad gets to the database. This causes a small problem with Postgres.
ALTER TABLE my_table ALTER COLUMN created_at SET DEFAULT now();
ALTER TABLE my_table ALTER COLUMN created_at SET DEFAULT 'now()';
Ok the first statement is what I meant - and the second statement is what get executed. Why does this matter you ask? Well you see the first one actually sets the coulmn to default to the function now(). Which means when you create something it will be set to the current date and time. The second one sets the default to the current value of now(). Which means all your created_at are going to be set to the same value unless you actually pass a value in (which doesn’t seem to be happening).
Anyone got a nice solution to this?
December 15th, 2005 at 2:10 pm (subscribed to comments)
Dirk, I don’t know if you’re situation is the same as mine, but it appears that Rails is still populating the value of my date field “created_tm” even though it’s not one of the magic fields (”created_at” or “created_on”). Something else is afoot in my situation…
December 20th, 2005 at 7:58 pm (subscribed to comments)
Any luck so far, Dirk?