可以使用Rails ActiveRecord #save方法来更新现有记录吗? [英] Can Rails ActiveRecord #save method be used to update an existing record?

查看:72
本文介绍了可以使用Rails ActiveRecord #save方法来更新现有记录吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#save 方法可以用于更新记录吗?

Can the #save method be used to update a record?

我知道我可以使用保存保存创建新记录,例如:

I know that I can create a new record using save, like this:

person = Person.new 
person.save # rails will insert the new record into the database.

但是,如果我先找到一个现有记录,则修改模型,然后保存它,是这个吗

However, if I find an existing record first, modify the model, and then save it, is this the same result as performing a update?

person = Person.find(:first, :condition => "id = 1") 
person.name = "my_new_name" 
person.save # is this save performing a update or insert?


推荐答案

是。 Rails中的ActiveRecord对象在ID参数中保留其标识。如果设置了ID,Rails将知道使用该ID更新数据库中的记录。

Yes. An ActiveRecord object in Rails retains its identity in the ID parameter. If the ID is set, Rails will know to update the record in the database with that ID.

保存是实际上,创建,更新或以任何方式将对象保存到数据库的主要方式。其他方法,如 update_attributes 只是糖,其核心使用 save

save is, in fact, the primary way to create, update, or in any way save an object to the database. Other methods like update_attributes are just sugar that use save at their core.

这篇关于可以使用Rails ActiveRecord #save方法来更新现有记录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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