Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Rails ActiveRecord #save method be used to update an existing record? [duplicate]

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?
like image 624
Yang Avatar asked Mar 24 '10 03:03

Yang


People also ask

What is Rails ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is Rails ApplicationRecord?

Now ApplicationRecord will be a single point of entry for all the customizations and extensions needed for an application, instead of monkey patching ActiveRecord::Base. Say I want to add some extra functionality to Active Record. This is what I would do in Rails 4.2.

What's the purpose of ActiveRecord?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Is ActiveRecord an Antipattern?

In software engineering, the active record pattern is considered an architectural pattern by some people and as an anti-pattern by some others recently. It is found in software that stores in-memory object data in relational databases.


1 Answers

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.

like image 104
Matchu Avatar answered Sep 17 '22 18:09

Matchu