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.
1 2 | user = User.create(name: "Rose", occupation: "Code Artist") |
As for new
we will have to call the save
method to add the new record to the database.
1 2 3 | user = User.new(name: "Rose", accupation: "Code Artist") user.save |
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.
1 2 3 | # return a collection with all users users = User.all |
1 2 3 | # return the first user user = User.first |
1 2 3 | # return user with id = 10 user = User.find(10) |
1 2 3 | # return the first user named Rose user = User.find_by(name: "Rose") |
1 2 3 | # find all users named Rose who are Code Artists and sort by created_at in reverse chronological order users = User.where(name: "Rose", occupation: "Code Artist").order(created_at: :desc) |
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.
1 2 3 4 | user = User.find_by(id: 10) user.name = "Rose" user.save |
A more concise way of writing:
1 2 3 | user = User.find_by(id: 10) user.update(name: "Rose", accupation: "Code Artist") |
If you want to update multiple records at once, you can use the update_all
method
1 2 | User.update_all "max_login_attempts = 3, must_change_password = 'true'" |
4. Delete
An Active Record object can also be destroyed and it is immediately deleted from the database
1 2 3 | user = User.find_by(name: "Rose") user.destroy |
You can also delete multiple records at once with the destroy_by
and destroy_all
methods
1 2 3 4 5 6 7 | # find and delete all users named Rose User.destroy_by(name: "Rose") # delete all users User.destroy_all |
Reference source: https://guides.rubyonrails.org/active_record_basics.html