What is ActiveRecord?

Free preview 2 min to read

A row, wearing a Ruby object's clothes

article = Article.find(1)
article.title
# => "Hello Rails"
article.published?
# => true

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.

That translation layer, with one class per table and one instance per row, is ActiveRecord, the part of Rails that does it. The pattern is called an ORM, an Object-Relational Mapper. It maps between two things that don't naturally speak the same language: Ruby objects and relational tables.

Where this fits against everything already covered

Rails MVC overview named the Model as one of three roles, "data and business rules." ActiveRecord turns that role into working code. Article, used in Rails console (IRB) and Rails routes: basics as if a model already existed, is an ActiveRecord model, and this course looks at that class from the inside.

What this course covers, and what it leaves alone

This course is narrow: the shape of a model class, where it comes from, how its attributes appear without being written, and a first look at validations. Creating rows, finding them and writing the migrations that shape a table each get their own course right after this one.

Key takeaways

  • ActiveRecord is Rails' ORM, translating between Ruby objects and table rows.
  • .title and .published? are Ruby method calls; ActiveRecord connects them to database columns.
  • Article, used throughout this arc, is an ActiveRecord model, the Model role in working code.
  • This course covers a model class's shape; creating, finding and migrations come next.
Lesson 1 of 7 · free

Keep going with lesson 2

ApplicationRecord: the parent class

Every model inherits from ApplicationRecord, an abstract shared base that itself inherits from ActiveRecord::Base.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...