DataMapper: Create new record or update existing

不打扰是莪最后的温柔 提交于 2019-12-07 05:08:21

问题


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

回答1:


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

or

(Foo.get(id) || Foo.new).update(attributes)



回答2:


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.



来源:https://stackoverflow.com/questions/2567686/datamapper-create-new-record-or-update-existing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!