0

I'm using data_mapper in my own sinatra project.

So, what is the best way to update a record or create a new one with initial value if it doesn't exist?

E.g., I have a model like

class Model
  include DataMapper::Resource
  property :id, Serial
  property :count, Integer
end

Is there a way that can check the existence of the model, then increase the count if exist or create a new model and set the count to 0

THX

Papulatus
  • 677
  • 2
  • 8
  • 18

1 Answers1

0

This should work:

model = Model.first
if model
  model.update(count: model.count + 1)
else
  model = Model.create(count: 0)
end
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168