Question

I'm getting started with Ruby and DataMapper and I stumbled upon a problem which I think does not make any sense. Let's say I have the following model :

class Foo
  include DataMapper::Resource

  property :id, Serial
  property :date, Date, required: true

  def initialize
    @date = Date.today
  end
end

I open up IRB to test my models, set up the database connection, and try to save a new foo:

> foo = Foo.new
> foo.date
=> #<Date: 2013-03-28 ((2456380j,0s,0n),+0s,2299161j)>
> foo.save

Then I get the following exception :

DataObjects::IntegrityError: foos.date may not be NULL

And that perfectly makes sense, because I marked the date as required. But the date is there! I assigned it in the constructor of the class! And if I don't initialize it with today's date and I try to save, I only get a validation error. No exception.

What I don't understand (and this is what I want you to answer to) is that if I replace

@date = Date.today

with

self.date = Date.today

it works! foo is saved correctly. Why is that? Is it a bug inside DataMapper?

Was it helpful?

Solution

After bringing up the issue with DataMapper's people, I've been told that this is by design. For dirty tracking to work, you must absolutely use the attribute writer and not set the instance variable directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top