Active Record is the M in MVC - The model
In Active Record, objects carry both persistent data and behavior which operates on that data.
Active Record takes the opinion that ensuring data access logic as part of the object will educate users of that object on how to write to and read from the database.
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.
Active Record gives us several mechanisms, the most important being the ability to:
When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code.
However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some cases no configuration at all) when creating Active Record models.
Model / Class | Table / Schema |
---|---|
Article | articles |
LineItem | line_items |
Deer | deers |
Mouse | mice |
Person | people |
Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
singularized_table_name_id (e.g., item_id, order_id)
This column will be automatically created.
(bigint for PostgreSQL and MySQL, integer for SQLite)
|bigint |8 bytes | large-range integer | -9223372036854775808 to 9223372036854775807|
It is very easy to create Active Record models. All you have to do is to subclass the ApplicationRecord class and you're good to go:
Suppose that the products table was created using an SQL (or one of its extensions) statement like:
Schema above declares a table with two columns: id and name. Each row of this table represents a certain product with these two parameters. Thus, you would be able to write code like the following:
What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.
The create method call will create and save a new record into the database:
Using the new method, an object can be instantiated without being saved:
A call to user.save will commit the record to the database.
Active Record provides a rich API for accessing data within a database.
Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.
A shorthand for this is to use a hash mapping attribute names to the desired value, like so:
Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.
If you'd like to delete several records in bulk, you may use destroy_by or destroy_all method:
Thank You 😼