Sequel: An Alternative to ActiveRecord
Tags: ruby, tutorial, codenewbie, womenintech
Published: 2019-05-14 21:55:39

---
title: Sequel: An Alternative to ActiveRecord
published: true
description: Quick Sequel usage tutorial.
tags: ruby, tutorial, code newbie, women in tech
---

On Friday, I was given a take home coding assessment. I was required to build a RESTful API with Ruby with one big catch: no Rails. A few take aways from this - 

1. I was super excited to even get the opportunity, because this is my second coding challenge of my job search. Practice makes perfect, so the more I get, the more confident and comfortable I’ll be the following time. 

2. I gained invaluable experience building with tools/frameworks I don’t know I would have every known existed and/or used. One of these tools was Sequel, which is what I’ll be writing about today. 

For my challenge, I was required to use Sequel instead of ActiveRecord and boy was it a challenge. My opinion on Sequel is still up in the air. My first instinct was to wonder why anybody would ever use this gem over ActiveRecord. While working with it, I really enjoyed one aspect which softened my opinion a bit. We shall see what it is by the time I’ve finished this blog post. 

## What is Sequel? 

Sequel is a Ruby gem that functions as a “simple, flexible, and powerful SQL database access toolkit.” In other words, it is comparable to the widely used ActiveRecord gem. Sequel allows you to run migrations, queries, and manipulate the database, just as ActiveRecord does. 

### Database Types Supported by Sequel

Sequel currently supports the following database types: ADO, Amalgalite, IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle, PostreSQL, SQLAnywhere, SQLite3, and TinyTDS. 

## Installing Sequel

In order to use Sequel, you must first install the gem to your project. To do this, go to your Gemfile and add `gem ‘sequel’`. You will need to install the gem by running `$ bundle install` in your terminal. 

Within your `application.rb` file, you will need to `require ‘sequel’`, just as you would with ActiveRecord.  

## Creating the Database 

One thing that I found unique about Sequel (and of course I hit an error to figure it out), is that the database must first be created before you attempt to connect to connect Sequel to the database. 

To create the database, run the following command (with your own database name) - `$ createdb pets_development`.

*Note*: For the purpose of this tutorial, I am using PostgresSQL. The creation of the database is a little unique compared to that of SQLite3, so please keep that in mind and [visit this page](http://tutorials.jumpstartlab.com/topics/sql/sequel.html) if you are using a different type of database. 

## Creation of Migration Files

Creating the migration files is very similar to ActiveRecord in the layout, however, there isn’t a simple command to run like `rake db:create`. I created my migration files manually, but it is important to note that you should still include a timestamp to the beginning of your file name, as Sequel requires it. 

```ruby
# 20190514_dogs.rb
Sequel.migration do
  change do
    create_table(:dogs) do
      primary_key :id
      String :name, :null => false
      String :breed, :null => false
      foreign_key :owner_id, :people
    end
  end 
end 

# 20190514_owners.rb
Sequel.migration do
  change do
    create_table(:owners) do
      primary_key :id
      String :name, :null => false
    end
  end 
end
```

## Connecting to the Database

Now that we have the database and the migration files created, we need to connect Sequel to the database. In order to do this, you need to navigate to your `application.rb` file and include the following code:

```ruby
# application.rb

# establishes Sequel connection to db
DB = Sequel.connect(adapter: :postgres, database: ‘pets_development', host: 'localhost')
```

*Note*: There are multiple ways to connect to the database, this is just the way I preferred. This [article](https://sequel.jeremyevans.net/rdoc/files/README_rdoc.html) contains other options. 

*Another Note*: You **cannot** connect to the database after creating your models, so please make sure to complete this connection step **BEFORE** creating your models (I learned this the hard way).

## Creation of Models

Models in Sequel are set up very similarly to ActiveRecord. 

```ruby
# dog.rb 
class Dog < Sequel::Model
  many_to_one :person

  def validate
    super
    errors.add(:name, "must be present") if name.empty?
    errors.add(:breed, "must be present") if breed.empty?
  end
end

# owner.rb 
class Owner < Sequel::Model
  one_to_many :dogs

  def validate
    super
    errors.add(:name, "must be present") if name.empty?
  end
end

```

## Running the Migrations

Now for our final step to getting our database set up, running our migrations. Unfortunately, running our migrations isn’t as easy as typing `$ rake db:migrate` as it is with ActiveRecord. Luckily enough though, we still have a command to do this. Run `$ sequel -m db/migrate/ postgres://localhost/pets_development`. 

*Note*: The ‘db/migrate/’ is the path to my migration files, please replace this with your own. 

## Seeding the Database 

I created seed files for this project so I am going to explain setting this up. The first thing we need to do is install a helpful gem, `Sequel-Seed`. Go to your Gemfile and add `require ‘sequel-seed’` then run `$ bundle install`. 

Next, we need to create our seeds files. Seeds files also need to have a timestamp at the beginning of the name. 

```ruby
# 20190514_dogs_seed.rb 
Sequel.seed do
  def run
    [
      [‘buddy’, ‘labrador’, 1],
      [‘spot’, ‘golden retriever’, 1],
      [‘princess’, ‘beagle’, 2]
    ].each do |name, breed, owner_id|
      Dog.create name: name, breed: breed, owner_id: owner_id
    end
  end
end 

# 20190514_owners_seed.rb
Sequel.seed do
  def run
    [
      [‘angie’],
      [‘bill’],
    ].each do |name|
      Dog.create name: name
    end
  end
end

```

Go to your `application.rb` file and insert the following code to load the seed extension and seed the database:

```ruby
# application.rb
require ‘sequel/extensions/seed’

# loads the extension
Sequel.extension :seed 

# seeds the database
Sequel::Seeder.apply(DB, “db/seeds/“)
```

## Queries 

Queries within Sequel are somewhat similar to those in ActiveRecord. Using `Dog.all` will return all dogs within the database. You can use `.first` and `.last` to get the first and last instances of an object in the database. `.order` allows you to order the instance within the database. You can use `.where()` to find all instances within the database that match the given object key. You can view more of these [here](https://sequel.jeremyevans.net/rdoc/files/README_rdoc.html).   

### Raw SQL Queries

One really neat thing about Sequel is that you can make raw SQL queries to the database. So, you can do something like this: 

```ruby
DB['select * from owners'].each do |row|
  p row
end
```

## Final Thoughts 

I really like the functionality of using raw SQL. I really like SQL queries and I always take advantage of getting to practice my SQL skills. This aspect of Sequel really changed my outlook on it. It really isn't all that different than ActiveRecord, but I still prefer using ActiveRecord. My reasoning for this is because of the `rake db` commands. They make life **so much easier**. 

I do see Sequel as a great tool to use as an alternative to ActiveRecord, though. I hope that this post has peaked your curiosity and maybe intrigued you to try Sequel out. 

Happy Coding!

#### Sources
[Sequel: The Database Toolkit for Ruby](https://sequel.jeremyevans.net/)
[Getting Started with Sequel](http://tutorials.jumpstartlab.com/topics/sql/sequel.html)