Create a Ruby on Rails Crud App in under 5 minutes
Ruby on Rails has a unique paradigm that helps developers build faster. Preferring convention over configuration sets us up with useful defaults that skeleton the project. It’s like doing a jigsaw puzzle with all the pieces on the outer edge complete.
In this post, we’ll discuss:
- What CRUD is.
- Creating a new Rails App.
- Setting up the database migration.
- Running the server.
This post isn’t meant to help you understand all the underlying principles of Rails and how it works. It’s just meant to help you build your first app and see how enjoyable Rails can be.
What is CRUD?
CRUD stands for Create, Read, Update and Delete. When building an Application, you want to be able to store information after a user is logged off. This is called persistent storage. (Persistent because it stays even after you’re gone.) It involved interacting with some sort of database and putting information into it. At the hurt of the interaction are 4 basic functions — CRUD.
For example, if we make a blog application, we might want to be able to create new posts, read existing posts, edit existing posts or delete existing posts.
Let’s see this in action.
Creating our new Rails App
We’ll rely on Rails generator and scaffold to speed this process along. I’m assuming you have Rails already installed on your system, if not read the post on how to get started in Rails.
To start a new Rails project we run this command:
rails new blog
This will create a folder in the current directory called “blog” with a starter rails app.
We can run a server and see the Rails Welcome message very easily. Just type:
Now if you go to localhost:3000 in your browser, you’ll see the rails welcome guide.
Set up Blog Resource
Let’s create a very simple CRUD blog using Rail’s scaffold. You will need to type:
rails generate scaffold post title:string body:text
This will create a basic scaffold for our post that has a title and a body. We can’t quite run the server and see the fruits of labor yet because we have a pending migration.
A migration is just simply a task that’s waiting to be implemented onto our database. In our case, we need to create the a database table named “posts”. By convention, we have a ruby class named Post that corresponds to the “posts” table.
Type in this command to run our migration:
You’ll see that it created our posts table for us. Now we can see the result by running the server.
If we navigate to localhost:3000/posts , we’ll see our post. We can create new posts, read existing ones, edit and delete. Try it out.
I hope you enjoy your first or second Rails App.