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