Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Rails Console: Deleting Model Objects1:21 with Jay McGavren
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:
- 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.
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.
Let's get a list of all the post objects again.
And let's load a particular instance using its ID and assign it to a variable.
Post equals post.find (4).
Now we'll call the destroy method on that object,
post, lower case because it's a variable named destroy.
We'll see an SQL query that deletes the record from the database.
Note that the method name is destroy not delete.
A method called delete exists, but
it works in different and potentially confusing ways.
You'll want the destroy method in most cases.
If we call post at all again,
we'll see that the record we destroyed is gone from the collection.
That wraps up our two of the rails console for now.
Before we can run bin rails generator other commands we need to exit
the console program.
Type exit all by itself on a line and
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