5

DataMapper 是否提供了一种在不存在或更新现有记录时创建新记录的便捷方法?我在 API 文档中找不到任何内容。

这就是我目前所拥有的,看起来不太优雅:

foo = Foo.get(id)
if foo.nil?
  foo = Foo.create(#attributes...)
else
  foo.update(#attributes...)
end
foo.save
4

2 回答 2

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

或者

(Foo.get(id) || Foo.new).update(attributes)
于 2010-04-11T14:24:16.113 回答
1

我只是尝试

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

但有时它会出错,所以我从这里找到一些提示:DataMapper Docs

现在我让我的代码像这样工作:

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

希望它可以帮助你。

于 2013-08-13T05:38:51.257 回答