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

Client libraries Many options

Ruby developers has a number of options for Postgresql client libraries:

  • ruby-pg - is the most popular ruby client for postgres.
  • em-pg-client - is the Ruby and EventMachine driver interface to the PostgreSQL RDBMS. It is based on ruby-pg.

But you probably want to use a ORM Again many options

Ruby developers has a number of options for ORMs

  • Sequel - The Database Toolkit for Ruby. Jeremy Evans is awesome!
  • ActiveRecord - probably the most used ORM, comes with rails.
  • Datamapper - Development seems to have halted. They started on the 2.0.0 branch started some time ago...

Okay I know my options, show me some code.

With sequel

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

With ActiveRecord

require 'active_record'
require 'uri'
uri = URI.parse(ENV['ELEPHANTSQL_URL'] || 'postgres://localhost/contacts')

ActiveRecord::Base.establish_connection(adapter: 'postgresql', host: uri.host, username: uri.user, password: uri.password, database: uri.path.sub('/', ''))

class Person < ActiveRecord::Base
end

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

With DataMapper

require 'dm-core'

DataMapper.setup(:default, ENV['ELEPHANTSQL_URL'] || 'postgres://localhost/contacts')
class Person
  include DataMapper::Resource

  property :id Serial
  property :first_name String
  property :last_name String

end
DataMapper.finalize
persons = Person.all(:first_name => 'John', :last_name.not => 'Smith')
persons.each do |p|
  puts [p.first_name, p.last_name].join(' ')
end