Learn Ruby on Rails Book

Active Record Basics

Basics of Active Record

Active Record makes dealing with database easier.

Let's fire up console.

1irb(main):002:0> Task.count
2   (0.1ms)  SELECT COUNT(*) FROM "tasks"
3=> 0

In the above case we can see that Rails converted Task.count into sql statement SELECT COUNT(*) FROM "tasks".

This is done using Active Record.

Overriding table names

Active Record following certain conventions. For example if the model name is Task then Rails assumes that the table name is plural version of it. In this case it would be Tasks.

However if the table name is something else then Active Record can be instructed to use the other name. Let's assume that the table name is "app_tasks".

1class Task < ApplicationRecord
2  self.table_name = "app_tasks"

Rails follows this convention over configuration for other things too.

Special columns

If the column name is created_at or updated_at then it has a special significance for Active Record.

Active Record will automatically populate created_at when that record is created. Similarly when a record is updated then Active Record will automatically update updated_at column.

The official Rails guide on Active Record has a section on Convention over Configuration. Please read that article.

There is nothing to commit in this chapter since all we had done was learning the basics of ActiveRecord.