views:

405

answers:

2

hi, guys, can the save method be used to update a record?

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

however, if i find a record first, modify it and save it. is it the same 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?

Thanks in advance!

A: 

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
JZ
+2  A: 

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.

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.

Matchu