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
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
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.
If the column name is
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
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