ActiveRecord w/ PostgreSQL

Start tinkering

Connect to a PostgreSQL database, query and create records using ActiveRecord.

require "bundler/inline"

gemfile do
  source ""

  gem "activerecord"
  gem "pg"

require "active_record"

ActiveRecord::Base.establish_connection(adapter: "postgresql", database: "ruby_starters_development")
ActiveRecord::Base.logger =

# Get list of tables in the database
tables =
  .execute("select * from pg_catalog.pg_tables where schemaname = 'public'")

# Define ActiveRecord Model classes for all tables
puts "\n\nAvailable Models (and tables):\n\n"
tables.each do |table, model: table.classify|
  puts "#{model} (#{table})"

# When connecting to a Rails generated db, chances are there is a schema_migrations table:
puts SchemaMigration.last.inspect

# Suppose there is a users table we can query that:
puts User.where(first_name: "Wolfgang").count

# WE can create records, too!
# But mind you are bound by db constraints only,
# there are no validations unless you defined them here:
# User.create!(email: "", first_name: "Wolfgang")