CRUD in Rails

Tram Ho

CRUD stands for four actions used to manipulate data: Create, Read, Update and Delete. In Rails, the Active Record automatically creates methods that allow you to manipulate data in the database without having to write regular queries. All you need to do is just call the corresponding methods and Active Record will help you to execute the queries against the database.

1. Create

Active Record objects can be made of a hash, a block, or can directly pass the values ​​of the object’s properties when calling create . new method will only return a new object that is not stored in the database, if you want to save you have to call the save method, while create will return a new object and store it in the database. So you can understand create is a combination of two methods new and save . For example, there is a User model with two fields: name and occupation, when the create method is called, a new record is created and saved in the database.

As for new we will have to call the save method to add the new record to the database.

2. Read

Active Record provides a lot of APIs to be able to access data in the database. Here are a few simple examples of some of the methods that Active record provides.

You can learn the methods that Active Record provides here Active Record Query Interface

3. Update

Once an Active Record object has been created, you can change its properties and save it to the database.

A more concise way of writing:

If you want to update multiple records at once, you can use the update_all method

4. Delete

An Active Record object can also be destroyed and it is immediately deleted from the database

You can also delete multiple records at once with the destroy_by and destroy_all methods

Reference source: https://guides.rubyonrails.org/active_record_basics.html

Share the news now

Source : Viblo