Before we step into ActiveRecord, let’s take a step back and briefly discuss model-view-controller (MVC). MVC is a software design pattern used to divide a software program into three components: the model, view, and controller. By doing this, the separated internal representations of information allow for separation of responsibilities, thus, allowing multiple developers to work on the model, controller, and views with less reliance on other parts of the program, lowering the risk of loose coupling.
Ok… so, what is ActiveRecord?
ActiveRecord is a part of the M (Model) in MVC. By following a few naming guidelines, ActiveRecord accurately maps out data between our models and database tables, which we probably would have had to do by hand using SQL if systems like ActiveRecord did not exist (tedious at best and time-depleting at worst).
Not only that, ActiveRecord can:
- Represent models and their data.
- Represent associations between these models.
- Represent inheritance hierarchies through related models.
- Validate models before they get persisted to the database.
- Perform database operations in an object-oriented fashion.
When using ActiveRecord, don’t forget —
The naming rules for ActiveRecord:
A model class, like PickleRick, is singular with EachWordCapitalized
A database table, like pickle_ricks, is pluralized with snake_case.
The schema (in reference to the schema of a database table) conventions:
Foreign keys: like item_id, it should be in singularized_table_name_id.
Primary keys: notated with an integer column named id (or bigint in PostgreSQL & MySQL, integer in SQLite). ActiveRecord automatically does this for you when you run a migration. Less work for us. ActiveRecord is nice like that.
Other interesting features…
created_at- Automatically gets set to the current date and time whenever the record is created or updated.
updated_at- Automatically gets set to the current date and time whenever the record is created or updated.
(association_name)_type- Stores the type for polymorphic associations.
Image 1. ActiveRecord meme