1

This should be an easy one, but I've googled a fair bit.

I am trying to create a database log for my rails app. The log is a postgres table which has a timestamp field, which I have given a DEFAULT of current_timestamp. This works perfectly in raw SQL, if I leave the timestamp field out of my INSERT query, it gets the current timestamp correctly.

In rails I have;

entry = LogTable.new :fieldA => 'valA', :fieldB => 'valB'
entry.save

(LogTable extends ActiveRecord::Base)

Which results in an INSERT query that contains all fields, including the timestamp field set to NULL, which is not allowed by the database so it errors.

I have tried setting :timestamp => 'current_timestamp' and :timestamp => 'DEFAULT' but all end up trying to set it to NULL.

lynks
  • 5,599
  • 6
  • 23
  • 42

1 Answers1

1

Is your current_timestamp just the current date/time? If so, you can stay simple and do something like:

entry = LogTable.new :fieldA => 'valA', :fieldB => 'valB', :timestamp => Time.now

If it's something more complex and you really want to use DB-side defaults, this page might help: http://drawohara.com/post/6677354/rails-activerecord-default-values.

moonfly
  • 1,810
  • 11
  • 14
  • I assumed that this would not work, as the field is actually a postgres `DATETIME_WITH_TIMEZONE` field, not just a simple unix timestamp. I am unable to check until tomorrow morning, but thanks for the input. – lynks Feb 28 '13 at 19:33
  • should work, as it's essentially the same as I deduce from here: http://stackoverflow.com/questions/9571392/ignoring-timezones-altogether-in-rails-and-postgresql/9576170#9576170. you may need to do `Time.zone.now` instead of `Time.now`, though I doubt (will be converted to UTC anyway, if I understand it right). still you may need to experiment. – moonfly Feb 28 '13 at 19:44