Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataMapper: Create new record or update existing

Does DataMapper provide a convenient way to create a new record when none exists or update an existing one? I couldn't find anything in the API documentation.

This is what I have at the moment which doesn't seem very elegant:

foo = Foo.get(id)
if foo.nil?
  foo = Foo.create(#attributes...)
else
  foo.update(#attributes...)
end
foo.save
like image 695
John Topley Avatar asked Apr 02 '10 16:04

John Topley


2 Answers

Foo.first_or_create(:id=>id).update(attributes)

or

(Foo.get(id) || Foo.new).update(attributes)
like image 95
gerrit Avatar answered Nov 18 '22 02:11

gerrit


I just try

Foo.first_or_create(:id=>id).update(attributes)

but it gets wrong sometimes, so I find some tips from here:DataMapper Docs

Now I make my code works like:

Foo.first_or_create({:id=>id}, {:name => name}).update(:id => id, :name => name)

Hope it helps you.

like image 1
Rui Fang Avatar answered Nov 18 '22 03:11

Rui Fang