Connecting Tables to ActiveRecord models

In ActiveRecord we use a particular type of class or Ruby object to link our SQL database and it’s contents to something we can work with in our Sinatra project. These are known as “models”. Each models maps directly onto a single table in our database and contains all of the functionality we need to access, add or remove data from that table.

About ActiveRecord Models

Models are part of Active Record’s Object Relational Mapping.

It’s a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.*

As this rails guide explains , Active Record gives us several mechanisms, the most important being the ability to:

  • Represent models and their data.
  • Represent associations between these models.
  • Represent inheritance hierarchies through related models.
  • Validate models before they get persisted to the database.
  • Perform database operations in an object-oriented fashion.

Simply put, models are the glue between the database and ruby. They are a set of classes that represent your data and give you access to standard operations you’ll want to perform on that data.

Creating Models

Now that we have a Task table, need need to set it up as an ActiveRecord model so we can access and add data to it. To access this table from Ruby, you need to have a class that models the database table. ActiveRecord makes this really easy!

First things first! Let’s make sure they’re organized. Create a new folder called models to hold all of our models in one place.

To add a model, just create a new file called task.rb and add the following code inside of it:

class Task < ActiveRecord::Base
  
end

The fact that Task is in the singular form is very important. Table names are plural (“the tasks table”) and model names should be singular (“the Task model”). This convention is what let’s ActiveRecord automatically map data into your models.

Next, we need to add this file to our main application. We do this by requiring it. Just add the following line to your main app.rb beneath the line where you set your database using the following code:

require_relative './models/task'

That’s all you need to hook it up to data.

Now activerecord will link the model to the SQL table on or behalf. It’ll look up what columns are available from our schema and automagically adds methods to this class for your data. We can do all sorts of things.



Task.all  # Get all of the records in our database 

Task.all.each do |task|
	#loop over each record
	# and write out the id to the command prompt
	# note we can access any column using .column_name
	puts task.id
	
	# we can assign data to a record 
	task.name = "New name"
	
	# and we can save that record easily with one line of code
	task.save
end

Task.find( id: 1 ) # search for a record based on the id
Task.where( is_complete: true ) # or find those that are completed. 

Task.destroy_all  # remove all the tasks

Neat!

Important: Naming conventions for Models

To reiterate the above, here’s a section directly from the ActiveRecord guide

By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. ActiveRecord will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The pluralization mechanisms are very powerful, being capable of pluralizing (and singularizing) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:

  • Database Table - Plural with underscores separating words (e.g., book_clubs).
  • Model Class - Singular with the first letter of each word capitalized (e.g., BookClub).
Model / Class Table / Schema
Article articles
LineItem line_items
Deer deers
Mouse mice
Person people

Read more

Active Record Basics: Creating Active Record Models Active Model Basics

×

Subscribe

The latest tutorials sent straight to your inbox.