Learn Ruby on Rails Book

Active Record basics

Basics of Active Record

Active record is the superclass of ApplicationRecord which is in turn the superclass of every model in our Rails application. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database with its rich collection of useful methods.

Active Record makes dealing with database easier.

To see it in action, let's fire up console:

1bundle exec rails console

Now, execute this command:

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. If the table name is "app_tasks", we will specify it in our model definition like this:

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

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.

⌘K
    to navigateEnterto select Escto close
    Previous
    Next