轨道3.1活动记录插入或更新 [英] rails 3.1 active record insert or update

查看:156
本文介绍了轨道3.1活动记录插入或更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的铁轨。

是否有活动记录一个简单的方法来传递数据的哈希值,如果记录存在,更新它,如果它不,创建它?

Is there an easy way in active record to pass it a hash of data and if the record exists, update it, and if it doesn't, create it?

data = {}
data["my_id"] = 356345
data["description"] = "test123"

w = Descriptions.new(data)

在理想情况下,如果我跑了上面那只曾经有1的记录,我跑了,每次不是多个记录。

Ideally if I ran the above it would only ever have 1 record, not multiple records each time I ran it.

推荐答案

假设你想要洁具的my_id位是唯一可以运行

Assuming you ware wanting the "my_id" bit to be unique you can run

Descriptions.find_or_create_by_my_id(data["my_id"]).update_attributes(data)

这篇关于轨道3.1活动记录插入或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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