DEV Community

tuckersteil
tuckersteil

Posted on

Using Active Record

Table of Contents

  • Introduction
  • Active Record ORM
  • Linking a model to a database
  • Using new methods from ActiveRecord::Base
  • Summary

Introduction
Active record is an extremely useful tool, which provides an interface and binding between the tables in a relational database and the ruby program code that manipulates database records. Active record is an object relational mapping technique( or ORM), which makes fetching and representing data easier by saving us the trouble of writing our own custom ORM's. I'll be going over how to build tables with Active Record, which in turn enables us to interact with a database to retrieve properties and relationships of the objects in an application without writing SQL statements.

Active Record ORM
Active record is a ruby gem, meaning that we can access an entire library of code by running "gem install activerecord" or simply including it in our Gemfile. After running "gem install activerecord",our gem environment knows what to put into the picture. Now all we need to do is tell active record where the database that it'll be working with is located. this can be accomplished by running "ActiveRecord::Base.establish_connection". Then once "establish_connection" is ran, active record will store the database as a class variable at "ActiveRecord::Base.connection". To actually run and establish the connection we need to add the code below to our active_record.rb file

ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: "db/coaches.sqlite"
)

Now that we have our database set up, we need to create a table since our database is currently empty. To do so we also need to add the following code into our active_record.rb file.

sql = <<-SQL
CREATE TABLE IF NOT EXISTS coaches (
id INTEGER PRIMARY KEY,
name TEXT
)
SQL

ActiveRecord::Base.connection.execute(sql)

Linking a model to a database
Recap thus far: We have created a database and a table named coaches.

The next step in the process is to link a coach model to the coaches database, where the coach model will serve as a gateway into talking to the coaches table in the database.
This can be accomplished by making our class of coaches a subclass of ActiveRecord::Base. Like so:

class Coach < ActiveRecord::Base
end

By doing so we will now have access to the plethora of active records built in ORM methods. By simply following one very important naming convention — class names are singular and table names are plural — we've done enough to establish a relationship between our Coach class and the coaches table.
Active Record "knows" that when we're using the Coach class, the SQL code it writes for us should target the coaches table.

Using new methods from ActiveRecord::Base
Now that we've created a database, table, and linked a class to the database table we can make use of active records built in ORM methods. Here is a look at some of the potential methods we can utilize.

Retrieve a list of all the columns in the table:

  • use .column_names
  • Coach.column_names #=> [:id, :name]

Create a new Coach entry in the database:

  • use .create
  • Coach.create(name: 'Tim') # INSERT INTO coaches (name) VALUES ('Tim') # => #<Coach:0x00007f985d0638b0 id: 1, name: "Tim">

Return all the records from the coaches table as instances of the Coach class:

  • use .all
  • Coach.all # SELECT "coaches".* FROM "coaches" # => [#<Coach:0x00007f985d0638b0 id: 1, name: "Tim">]

Retrieve a Coach from the database by id:

  • use .find
  • Coach.find(1) # SELECT "coaches".* FROM "coaches" WHERE "coaches"."id" = 1 LIMIT 1 # => #<Coach:0x00007f985d0638b0 id: 1, name: "Tim">

Find by any attribute, such as name:

  • use .find_by
  • Coach.find_by(name: 'Tim') # SELECT "coaches".* FROM "coaches" WHERE "coaches"."name" = 'Tim' LIMIT 1 # => #<Coach:0x00007f985d0638b0 id: 1, name: "Tim">

You can get or set attributes of an instance of Student once you've retrieved it:

  • use attr_accessors
  • coach = Coach.find_by(name: 'Tim')
  • coach.name #=> 'Tim'

  • coach.name = 'Bob'

  • coach.name #=> 'Bob'

And then save those changes to the database:

  • use #save
  • coach = Coach.find_by(name: 'Tim') coach.name = 'Bob' student.save # UPDATE "coaches" SET "name" = "Bob" WHERE "coaches"."id" = 1

Summary
We've now seen how Active Record creates a link between Ruby and databases, which is an extremely useful and easy tool to use. Which allows us to make use of the built in ORM's, rather than having to write out all of our own.

Top comments (0)