When developing an applications, developers need a way to save modify and query the data. The application may use the a database management system (DBMS) to store the data but how to modify and retrieve data in the DBMS? DBMS has a set of raw commands to run operations on the system, for example SQL commands. We could use it in raw but it will make the codes look dirty.
Solution : Object Relational Mapping (ORM)
Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code. — Rails ActiveRecord Documentation http://guides.rubyonrails.org/active_record_basics.html
Basically, ORM job is to connect application (in this case Rails app) to the database. It will map objects in the application to relational schema in the database. ORM will make development easier because developers do not need to use DBMS commands directly to access the database.
ActiveRecord: Rails’ ORM
ORM in Rails comes in form of ActiveRecord models. A model is a way to represent a data with all of its attributes, associations, and validations. Rails ORM supports multiple DBMS, such as MySQL, PostgreSQL, and MongoDB. Using Rails model, you can do the following:
- Database Migration, migration is scripts to create tables or documents in DBMS. keys, index, and associations can be specified directly from the migration.
the migration will also add created_at and updated_at fields as timestamp metadata when t.timestamps is defined.
- Create, update, delete
- Validation, Rails provides a bunch of validation that can be used to validate attributes value to maintain data integrity in database
- Query the Data
Rails provides some commands to query the data, it supports conditional, sorting, and many else.