How to delete a Rails database entry

As I continue to work on my little app, Isement, that I built while doing the Baserails.com course, I hit a snag today and wanted to delete some database entries.

More specifically I wanted to delete a few users in my Users database. While building the app, I’ve signed up with a few different demo accounts. I want to start from scratch. Delete all but one of the demo accounts. I did some searching, and surprisingly the answer didn’t jump right out at me.

With Rails 4, here is how I deleted specific user accounts by their ID numbers:

1) In Terminal (command line tool) go ahead and enter the command: “rails console”. You now can manually edit your database right from the command line.

2) Use this command to be specific in what entry you want deleted:

User.find_by(id: ‘2’)

Of course that would change some depending on what table you are trying to manipulate. If you have a table that is for Posts, then you would replace that command with “Posts.find_by(id: ‘2’).

3)After that command you simply enter:

user.destroy

Again, replace “user” with whatever table you’re editing.

You can read more about this here on the Ruby On Rails Guides site.

rails

Hey folks! I ended up going with Michael Hartl’s massively popular (for a reason) Ruby on Rails tutorial course to learn Rails. I highly recommend you do the same.
Check it out here.

2015-07-22T04:31:43+00:00