Home » Ruby on Rails CRUD

Ruby on Rails CRUD

CRUD stands for Create, Read, Update and Delete data in a database. Active Record automatically allows an application to read and manipulate data stored within tables.

In this tutorial, we will create a Rails CRUD with MySQL database.

Step 1 Create a new Rails application.

Step 2 Change your directory to crud.

Step 3 Go to the Gemfile in your application and add the following.

Step 4 Go to the config/application.rb file in your application and add the following.

Step 5 Run the following command:

Step 6 Go to app/views/layouts/application.html.erb and insert the following lines in head tag.

Step 7 Go to app/views/layouts/application.html.erb and insert the following lines before </body> tag.

Step 8 In the above file, replace <%= yield %> with following code:

Step 9 Go to app/assets/javascripts/application.js and add the javascript code that loads jQuery DataTable:

Step 10 Create a controller from the console.

Step 11 Create a model from the console.

Step 12 Go to app/controllers/products_controller.rb and write the following code.

Step 13 Go to app/models/product.rb and make some validations on the name, price and description fields.

Step 14 Go to config/routes.rb and add:

Step 14 Go to config/routes.rb and add:

Step 15 Now create a folder named api in app folder. Inside this folder create a folder named products. Now finally create app/api/products/products_api.rb file and add the following code.

Step 16 Go to config/routes.rb and add the following code.

Step 17 Run following command in your console.

Step 18 In app/views/products/ file, write the following code.

index.html.erb

new.html.erb

edit.html.erb

show.html.erb

Step 19 Start the server from the command line.

Step 20 Run the application on your localhost.

Following page will appear. Here we have already inserted some data in the table.

Rails Ruby on rails crud 1

Insert Data

Rails Ruby on rails crud 2

To insert data, click on Add Product as shown in the above snapshot. Fill the details as shown below.

Rails Ruby on rails crud 3

Read Data

To read data, click on action Show. Here we will click on Jeggings Show action.

Rails Ruby on rails crud 4

Update Data

To update data, click on Edit action. Here we will Edit, Shirts description from Men formal shirts to Women formal shirts.

Rails Ruby on rails crud 5 Rails Ruby on rails crud 6

Delete Data

To delete data, click on Delete action. Here we will delete product Jeans from the above table.

Rails Ruby on rails crud 7


Download

Download this example

You may also like