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
We'll end our tour of the Rails console with "delete" operations.
Your users need to be able to delete data as well, so Rails also allows the removal of records from the database. We just load up a particular instance of the model, as before, and then call the "destroy" method on it.
- As before, we can load a particular instance using its ID, and assign it to a variable:
post = Post.find(7)
- Now, we'll call the "destroy" method on that object:
post.destroy
. - We'll see an SQL query that deletes the record from the database.
We'll end our tour of the rails
console with the delete operations.
0:00
Your users need to be able
to delete data as well so
0:04
rails also allows the removal
of records from the database.
0:07
We just load up a particular
instance of the model as before and
0:11
then call the destroy-method on it.
0:14
Let's get a list of all
the post objects again.
0:17
And let's load a particular instance
using its ID and assign it to a variable.
0:22
Post equals post.find (4).
0:28
Now we'll call the destroy
method on that object,
0:34
post, lower case because it's
a variable named destroy.
0:37
We'll see an SQL query that deletes
the record from the database.
0:44
Note that the method name
is destroy not delete.
0:49
A method called delete exists, but
0:52
it works in different and
potentially confusing ways.
0:53
You'll want the destroy
method in most cases.
0:57
If we call post at all again,
1:00
we'll see that the record we destroyed
is gone from the collection.
1:03
That wraps up our two of
the rails console for now.
1:07
Before we can run bin rails generator
other commands we need to exit
1:10
the console program.
1:13
Type exit all by itself on a line and
1:15
press enter and
you'll be back to your system prompt.
1:17
You need to sign up for Treehouse in order to download course files.
Sign up