DEV Community

Cover image for Create a table with ActiveRecord.
R-Villar
R-Villar

Posted on

Create a table with ActiveRecord.

What is ActiveRecord?

ActiveRecord is the M in the MVC (Model-view-controller). The model is the layer of the system responsible for representing data and logic. Active Record facilitates the creation and use of objects whose data requires persistent storage to the database.

ActiveRecord facilitates building tables using Ruby. As well as, enabling us to interact with a database to retrieve properties and relationships of the objects in an application without writing SQL statements.

How to create a table with ActiveRecord?

Creating a table is simple, but before you do that you have to create a migration before setting up your table. to create the migration you have to run this command on the terminal rake db:create_migration NAME=<name-migration>

After you do this you will have new file like this.

Image description

Inside of this file we will create our table method.

Image description

After the table name artists we write a a block of code that is passed a block parameter t. It is a special Active Record migration object that helps add different columns to the table.

Image description

After this we run rake db:migrate
Active Record will create a new database file.

Image description

This will also create a db/schema.rb this is used as a snapshot of the current state of the database.

Image description

We then create an Artist class and extend the class with ActiveRecord::Base

Image description

We then are able to instantiate a new Artist.

Image description

After creating a few more Artists we can see all of their information.

Image description

sources:
ActiveRecord

Top comments (0)