0

It seems that validations in DataMapper run before dm-timestamps has a chance to autoset the created_at and updated_at fields.

Consider the following:

require 'dm-core'
require 'dm-migrations'
require 'dm-timestamps'
require 'dm-validations'

class MyResource
  include DataMapper::Resource

  property :mykey, Serial, :key=>true
  property :created_at, DateTime, :required=>true
  property :updated_at, DateTime
end

resource = MyResource.new
resource.save #fails

The save fails because created_at is blank. Interestingly, if you just comment out the "require dm-validations", the problem goes away. Of course, you can also just remove ":required=>true" from :created_at but that's not what I'm after - created_at is required. It's just that I'm using dm-timestamps to automatically set it for me.

Anyone else seen this? Is there a solution?

Jeremy Burton
  • 863
  • 6
  • 10

2 Answers2

0

Most likely, the created_at timestamp is set after validations are run. That's actually a pretty sensible behavior since it won't, in fact, be created if it fails validation. You can either remove the :required => true since it's not actually buying you anything or you can set up a before_validation hook that sets the timestamp. The second option may have unintended consequences. I don't think so, but I don't know DataMapper well enough to be sure.

Emily
  • 16,793
  • 3
  • 39
  • 46
0

Under what circumstances would you reasonably expect created_at to be NULL? Are you just defending against manual manipulation of the records in the database?

If that's the case, I'd probably omit the :required=>true bit and just enforce that constraint in the database. Let dm-timestamps do it's thing. It's pretty solid. That seems like a pragmatic solution. As they say, "Do the simplest thing that could possibly work."

Larsenal
  • 45,294
  • 40
  • 140
  • 210