Important Notice: ElephantSQL is shutting down. Read all about it in our End of Life Announcement

Part 3.3 Databases for beginners - PostgreSQL and Ruby

Written by Lovisa Johansson

Part 3 of Databases for beginners show how to connect to your database via Ruby.

Our previous article explained the SQL language. We executed some standard SQL queries from the web browser, and it's time to show how to do this programmatically, and how to use your database in combination with your application. Our first article also showed how to create a database for free, in the cloud. In this part of the series we show how to connect to your database via Ruby.

Ruby and PostgreSQL

A client library for PostgreSQL has to be downloaded. A client library has several methods that can be used, in this case to communicate with PostgreSQL. The methods should be used when you, for example, connect to the database (using the given parameters, host name, port number, etc) or when you select data from your database. There is a choice of libraries for almost every programming language.

Start by downloading the client-library for Ruby. Ruby developers have a number of options of client libraries. In this example Sequel will be used. Other recommended client libraries for Ruby can be found here.

require 'sequel'
DB = Sequel.connect ENV['ELEPHANTSQL_URL'] || 'postgres://localhost/contacts'

class Person < Sequel::Model
end

persons = Person.where(first_name: 'John').exclude(last_name: 'Smith')
persons.each do |p|
  puts [p.first_name, p.last_name].join(' ')
end

To connect to your ElephantSQL database you simply provide Sequel.connect with your URL. The URL can be found in your details page for your ElephantSQL instance.

DB = Sequel.connect ENV['ELEPHANTSQL_URL'] || 'postgres://localhost/contacts'

The example has a class "Person", and this person has a first name and a last name.

class Person < Sequel::Model
end

persons = Person.where(first_name: 'John').exclude(last_name: 'Smith')
persons.each do |p|
  puts [p.first_name, p.last_name].join(' ')
end

ElephantSQL - PostgreSQL as a Service

We offer fully managed ElephantSQL instances with epic performance & superior support

Get a managed PostgreSQL server for FREE