Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Next let's look at "update" operations in the console.
After retrieving a model object from the database, we can modify its data and update the database record. This is much the same as working with a new model object; we just assign new values to the existing object's attributes, and call "save" on it.
Let's suppose we wanted to update a posts's title:
- As before, we can get a collection of all the Post objects by calling
Post.all
. - We can look at the "id" attribute of the one we want to update, and then retrieve it by passing the ID to the "find" method. We'll assign the object we get back to a variable:
post = Post.find(7)
- As before, we can set the attributes the same way we would on any other Ruby object. So let's change the title:
post.title = "I've been updated!"
- Once again, these changes only exist in your computer's memory, not in the database. We need to call the "save" method on the object to save it to the database:
post.save
Next, let's look at update
operations in the console.
0:00
After retrieving a model object from
the database, we can modify the object and
0:04
update the database record.
0:08
This is much the same as working
with a new model object.
0:10
We just assign new values, the existing
object's attributes and call save on it.
0:12
Let's suppose we wanted
to update a post title.
0:18
As before, we can get a collection of all
the posts objects by calling Post.all.
0:21
We can look at the ID attribute
of the one we want to modify and
0:27
then retrieve it by passing
the ID to the find method.
0:31
We'll assign the object we get back
to a variable, post = Post.find(3).
0:36
As before we can set the attributes
the same way we would on any other
0:43
Ruby object.
0:46
So let's change the title.
0:48
Post.title =" I've been
0:50
updated!" Once again,
0:54
these changes only exist in your
computer's memory, not in the database.
0:59
We need to call the save method on
the object to update its database record.
1:03
Post.save.
1:06
We'll see an SQL query that updates
the record in the database..
1:09
And the next time we query that database,
1:14
we'll see the updated title
instead of the old one.
1:16
You need to sign up for Treehouse in order to download course files.
Sign up