The basic concept can’t help but know about Active Record, Active Record basic

Tram Ho

Hello, Word:

Overview of ActiveRecord:

As a Ruby On Rails developer, you are no stranger to the “Active Record” name, so how do you understand it, how it works and how to structure it ??? especially those who have just approached Rails and are ActiveRecord ?, here I and you will go to learn more about it and the highlights of ActiveRecord! And as you all know for a programmer, one of the most important skills is logical reasoning, dividing the problem into small parts and solving each part, a small example: when you build A website application and of course Database is indispensable for your website from your blog site to the big guys like Facebook, instagram. . . With a huge amount of data and extremely complex, overlapping, from here we can imagine with the lack of a complex and improper database system will make you encounter many problems for your next programming step, from here we see that the database system is an important piece of your application, so here you can see how Rails works, connecting to data will make Your surprise is very interesting. This is one of the main reasons why Rails works well when compared to other options over the last few years. From here Rails provides us with an ActiveRecord an ORM for hosting web and database applications. , allows the model to reside in a more logical way, and makes it easy to grasp. So, what is ORM ? Let’s find it Follow me!


ORM? WHAT IS IT?

First you have to wonder what is ORM stands for? It stands for the phrase Object Relational Mapping temporarily translated into Vietnamese Bản đồ quan hệ giữa các đối tượng bit difficult to understand, right @@, after listening to the word, surely people still think about it and then maybe me too, In general, it is a programming skill that converts data between incompatible systems in object-oriented programming. It creates a virtual Object Database, which can be used inside the programming language, in a different or a bit more beautiful way, the ORM framework is a layer between the programming language and the database. written in an object-oriented programming language (such as Ruby, Python, PHP, etc.), you can use the same programming language to manipulate the database without writing sentences. SQL statement is long, The object class will correspond to the data tables in the database, and the object instance will correspond to the records in those data tables, let’s go to the power of it GOOO!


Strength:

ORM brings us a lot of utilities, including:

  • Independent of Database This is probably the greatest benefit of using ORM in an application. You do not need to write database commands. You are using SQLite, you do not like and switch to MySQL or PostgreSQL, now you do not need to edit the commands because ORM has done all for you. Even when changing a database, you only need to edit a few lines in the Database configuration adapter
  • Reducing the number of lines of code and increasing the efficiency of ORM programming allows programmers to focus on business logic rather than writing complex queries to the database, thus reducing the code and increasing work efficiency.
  • Diverse Query Interface The ORM framework offers a diverse number of query interfaces, addressing most of the probable cases associated with complex SQL statements.
  • Relationship between data ORMs help to effectively manage the relationships between data. Related objects are automatically loaded when a query is translated into the corresponding SQL statement.
  • Simultaneous processing ORM supports concurrent processing, allowing multiple users to update a collection of data at the same time.
  • Caching Objects are cached, reducing the load time on database.Transaction Many changes of objects can be put together in one transaction, so that they can be simultaneously committed (committed) and canceled ( rollback). Many transactions can run at the same time but each transaction is independent of the other.

And of course, everything has its strengths and weaknesses:

Weakness :

  • Increasing processing The ORM framework creates a layer between the programming language and the database, which helps reduce programming hassles and speeds development. However this also adds to the processing in the application. Using ORM will consume more data and CPU resources.
  • Familiarity To put an ORM into an application, developers will need more skills to use a new framework. It will take some time to get used to it. Performance Some operations, such as batch inserts, deletions, etc., will be slower when written in ORM. Typically, these jobs will be more efficient if directly using the pure SQL statement.
  • Ignoring SQL Using ORM makes it easier for programmers to manipulate the database, but it also leads to the programmer not delving into SQL, creating knowledge gaps.

And all this is an overview of ORM, can you tell me about ORM? Let’s find out about the main keyword today ACTIVE RECORD


ACTIVE RECORD:

So we can understand somewhat about ORM and now is Active Record what it has? how to use it ?

Well, a little bit, did you know that Rails is actually a collection of 7 Ruby gems that work together and are managed by gem. In particular, Active Record is the gem that plays the role of an ORM, its main task is to handle and manipulate issues related to the database system, and this operation is done by sentences. SQL statement (if you use SQL database), it has been simplified into manipulating common Ruby objects so far.

If you want to query a table to retrieve all Student, then you have to query SELECT * FORM students and then convert that result into an array, instead of in the active record , you just need to write a short sentence like after: Student.all done and then the solution of the active record it will retrieve for an array of all the student is amazing, right?

Well, there’s one thing you need to worry about here. What should I do if I use other data base? then to solve this problem, you only need to go to the config/database.yml file here you can set the database configuration, the remaining Active Record will handle you for the homogeneity and handling of different databases. , your job is to focus on code for your application only. What about the model side? Come on, let me continue exploring!


Rails Model:

Active Record communicates with database, it acts as part M in Rails MVC: models. The model is where most business logic in your application is handled, to store information about your students, you create a table in the database named students. You want to access that table from within your application. you, you create a model named Student, A table in the database will correspond to a model inherited from Active Record. Just that, you can use extremely convenient methods like all , find or create , destroy

After you create a project rails with the following command:

and create database: well and many ways to create my model, I will list as follows:

Look here we can understand that the letter g not the abbreviation of generate and vice versa too if you want to delete then just replace the other letter g into d ie delete , it’s great and interesting right k ? )) RubyOnRails motto that makes programmers happy not to get bored with programming, go a bit far … let’s go back. And when you run the above command, it will create you 2 files as follows:

The first file, which is a migrate file, is used to fix the database. The second file, is a Ruby class, this class inherits from Active Record. OK, here we can use the Active Record commands for model student . Let’s try 1 out 1 record in this student table offline:

Student.create(name: “dutavi”, code: 00686, age: 18, address: london)

done so we have 1 record: name: dutavi , code is: 00686 , age is: 18, and address is: london with calling the create method of the Student class and passing in that parameter is a The hash consists of keys and values ​​that are fields of the User model and corresponding values ​​that we have completed the step of creating a record, then what about migration?

Migration:

When do you need to migrate? That is when you need to change the database structure. You will define those changes using the Rails commands, the migration files that will be generated and run

rails db:migrate

to update what you have changed or want to add to the db, and this is the structure of a file migration:

And of course when you want to reverse the database change process you just created with the command:

rails db:rollback

VALIDATIONS:

And we cannot repeat this indispensable part. This is where we give the conditions to make sure that the data entered in the database is accurate and standard. ex: validates :name, presence: true write the following to make sure every student has a name, and of course Rails also supports a lot of other validations such as presence , uniqueness , inclusion , exclusion , length .. .In addition there are many options you can see more here: https://guides.rubyonrails.org/active_record_validations.html

CALLBACK:

The callback is an important part of Active Record (make sure to interview 10 people when 9 people are asked about this: v) it will be called at some point in the life cycle of an object. Callbacks are often used to execute logical methods before or after an object has made a change. For example, create, update, delete.

First we will create a method that we want to use in the callback:

and write a command to execute:

before_save :set_name

Literally, this means that every time we call the save command, the set_name method will be run before the save is completed, and there are many different types of callbacks that come in different situations. Below I will leave a few detailed articles and summaries of callbacks: https://guides.rubyonrails.org/active_record_callbacks.html , https://viblo.asia/p/tim-hieu-ve-callback- in-rails-RQqKLg9657z , and I would like to emphasize to you guys that developer rails must be sure of this one!

Associations:

This can also be said to be a good part, as we all know, the relational database has many tables that are interconnected. For example, in addition to the Student model, we also have one more model, Teacher, and a student can have many teachers. How can we make this link? Of course, first we have to create a model teacher:

rails g model Teacher name:string, student_id:integer

and student_id here is the foreign key we use to link the two models. and run rails db:migrate and we start to establish each of the two tables relationships together. Here I will do the following

In app/model/student.rb we add the following relationship:

has_and_belongs_to_many :teachers

and at app/model/teacher.rb

has_and_belongs_to_many :students

done, so we have established the relationship between the 2 tables here as nn relations, in addition there are many relationships and many different ways of establishing relationships: https://viblo.asia / p / association-in-rails-part-1-4dbZN0Aa5YM , https://guides.rubyonrails.org/association_basics.html .

Summary:

Speaking for a long time now, let’s get to the end, in short: Active Record is the most powerful feature of Rails and also one of the most confusing parts for you to get acquainted with Rails. The most difficult concept of ActiveRecord is probably Association, and a bit of my personal point of view, I’m really surprised and excited about the active record but in return the active record supports too many things, so using the sql query will is reduced, while reducing the feeling of normal queries, every time I want to see the full query, I have to log on to see, but I do not deny the power of active record, and certainly the audience reads. This article will be new to rails as well as active record , so through this friendly article (Maybe many points unknown or slightly confusing) I hope to bring you useful and useful knowledge. Can help you solve some of the stuck issues in this technique, wishing you a thorough grasp of this technique and h Complete your application in the most efficient and successful manner!

Share the news now

Source : Viblo