[Ruby] Rails Basic CRUD function implementation procedure scaffold

1 minute read

Preface

Summarize the steps to implement basic CRUD functionality using Ruby on Rails.
CRUD is an acronym for Create, Read, Update, and Destroy.

Launch the app

In the terminal, use the rails command to create an app.

rails new blog_app -d postgresql

This command creates a new blog_app.
I’m used to it, so I use postgreSQL as the database. If nothing is specified, sqlite3 will be the database. Then go to the root directory of the app (cd blog_app) and in the terminal

rails db:create

Enter to launch the database.
Launch the server and check locally that the app is ready.

rails s

rails.PNG

OK if the above screen appears. You can finish the server startup with ctrl + C.

CRUD function

Now that the app has been launched, we will implement the ability to post (create), read (read), update (update), and delete (delete) blogs.
In fact, using the rails generator scaffold, it’s done with just two commands.

rails g scaffold blog title:string content:text
rails db:migrate

With the first command, you can create Blog models, views, controllers and routers all at once. In this case, a string (character string) type instance variable title and a text (text) type instance variable content are created in the Blog model.
The second command is needed to create a blogs table in the database.

Postscript

Now let’s summarize the model, view, controller and router code without using scaffold.