DataMapper:创建新记录或更新现有记录 [英] DataMapper: Create new record or update existing

查看:85
本文介绍了DataMapper:创建新记录或更新现有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

or

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

这篇关于DataMapper:创建新记录或更新现有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆