ActiveRecord: model introduction
ActiveRecord is the Rails ORM that maps one class to a table and one instance to a row. This course looks at a model class from the inside. It covers the inheritance chain from ApplicationRecord to ActiveRecord::Base, the naming convention that links a class to its table, and how attributes come from the database schema. It gives a first look at validations as rules checked before saving. It ends by inspecting a model in the Rails console with read-only commands such as superclass, table_name and column_names.
What you'll learn
- ✓What an ORM is and how ActiveRecord maps tables and rows to Ruby objects
- ✓How models inherit from ApplicationRecord and ActiveRecord::Base
- ✓How class names map to plural snake_case table names, and how to override them
- ✓Why attributes come from the schema, column defaults included
- ✓How validates declares rules checked before saving
- ✓How to inspect a model in the console with superclass, table_name and column_names
What is ActiveRecord?
None of this looks like SQL: no SELECT, no WHERE, no quoted column names. article is a Ruby object, and .title and .published? are method calls, like every object since Rails MVC overview. Underneath, a row in an articles table was read and turned into this object, each column becoming an attribute.
Read the full lesson free →Curriculum
7 lessonsWhat is ActiveRecord?
ActiveRecord is the Rails ORM, turning table rows into Ruby objects with one class per table.
ApplicationRecord: the parent class
Every model inherits from ApplicationRecord, an abstract shared base that itself inherits from ActiveRecord::Base.
Convention maps a class to a table
Class names map to plural snake_case tables, module prefixes apply, and self.table_name overrides the convention.
Attributes come from the schema
ActiveRecord reads the schema and generates attribute methods for every column, reflecting database defaults too.
Validations: a rule before saving
The validates keyword declares rules such as presence, length, uniqueness and format, checked before saving.
Inspecting a model from the console
Read-only console commands like superclass, table_name and column_names check each fact about a model class.
Putting it together: a model, fully explained
Each line of the Article class traces back to inheritance, table naming, schema attributes and validations.