Active Records is the model Rails provides for database interaction. This model is an object-relational mapping (ORM).

What is an ORM? This means that every MySQL table is mapped to a class, rows map to objects and columns are object attributes. Its essentially a direct mapping between your code and the database.

Database

Create Active Record Files (Models)

In your Gemfile, add these lines:

gem 'mysql2'
gem 'activerecord-mysql2-adapter'

Then run:

rake db:drop
rake db:create

Restart the server.

Create Active Record files with the command line. To create the model type this command:

rails generate model Products name:string

If Rails hangs on this command, run:

rake app:update:bin

Then run the command again.

rails generate model Products name:string

This creates a bunch of files:

invoke  active_record
create    db/migrate/20181006130551_create_products.rb
create    app/models/product.rb
invoke    test_unit
create      test/models/product_test.rb
create      test/fixtures/products.yml

The file app/models/product.rb defines the skeleton.

$ cat app/models/product.rb
class Product < ApplicationRecord
end

Rails migration

If you output db/migrate/20181006131139_create_products.rb (your name may be different), it shows the table definition:

class CreateProducts < ActiveRecord::Migration[5.2]
  def change
      create_table :products do |t|
            t.string :name
            t.text :text

            t.timestamps
      end
  end
end

Run the commands

rake db:setup RAILS_ENV=development

rake db:migrate

This will create the table:

== 20181006132301 CreateProducts: migrating ===================================
-- create_table(:products)
   -> 0.0685s
   == 20181006132301 CreateProducts: migrated (0.0690s) ==========================

If you get the error:

ArgumentError: wrong number of arguments (given 4, expected 1)

Then remove gem 'activerecord-mysql2-adapter' from your Gemfile and try again.

In MySQL you can list the created table:

mysql> USE library_development;

mysql> SHOW TABLES;
+-------------------------------+
| Tables_in_library_development |
+-------------------------------+
| ar_internal_metadata          |
| products                      |
| schema_migrations             |
+-------------------------------+