Ruby-on-rails 可以使用 Rails ActiveRecord #save 方法更新现有记录吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2505079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can Rails ActiveRecord #save method be used to update an existing record?
提问by Yang
Can the #savemethod be used to update a record?
该#save方法可以用于更新记录吗?
I know that I can createa 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?
回答by Matchu
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.
是的。Rails 中的 ActiveRecord 对象在 ID 参数中保留其标识。如果设置了 ID,Rails 将知道使用该 ID 更新数据库中的记录。
saveis, in fact, the primary way to create, update, or in any way save an object to the database. Other methods like update_attributesare just sugar that use saveat their core.
save事实上,它是创建、更新或以任何方式将对象保存到数据库的主要方式。其他方法如update_attributes只是save在其核心使用的糖。
回答by JZ.
this is an update.
这是一个更新。
save(perform_validation = true)
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2533
2533: def save
2534: create_or_update
2535: end

