CRUD Operations in Rails
Before understanding CRUD operations in rails we will see what are active records. Active records point to the models of MVC architecture. Model is the component of mvc architecture which is responsible for persisting data storage into the database. Active records connects the objects of the data and help in persisting the data to the storage in the database. It stores the data in the form of objects.
Active Records have four basic operations :
- Create
- Read
- Update
- Delete
Create
Create operation in active records returns an object and helps us to directly save the object into the model i.e the table in the database. For example if we have to create a user through user model we will write the fallowing code:
User.create(name:"Tom Cruise",email:"tom@gmail.com")
This will directly save the name and email of the new user in the user table.
Read
Now to read the data from the database active records provide us with this Read operation through which we can get the data from the database and use it as per our requirement. Read has many inbuilt methods to get the data from the database. Those methods are explained below.
users = User.all
.all method give a collection of all the users from the users table in an array or a hash.
user = User.first
.first method will give first user from the users table.
user = User.find_by(name:"Tom Cruise")
.find_by method will find the name "Tom cruise" in the users table and get the user.
user = User.find(3)
.find method will search for user id "3" in the users table and will return the user.
Update
Update method of active records help us to update the data in the model through its object. This has basically two kind of methods i.e update and update_all.
user = User.find_by(name: 'Tom Cruise')
user.update(name: 'Tom Sawyer')
.find_by method will find the user name Tom Cruise in the users table and then .update method will update the name of that particular user.
Now if we have the requirement of updating all the users who live in Denmark so for that we have the method update_all
users = User.where(city: 'Denmark')
users.update_all(continent: 'Europe')
Delete
Delete operation of active records help us to delete records from a table. For this there is a method called destroy method.
user = User.find_by(name: 'Tom Cruise')
user.destroy
This method .find_by will find the user named Tom Cruise in the users table and .destroy method will delete this user from the users table.
0 Comment(s)