ActiveRecord w/ PostgreSQL

Start tinkering

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

require "bundler/inline"

gemfile do
  source "https://rubygems.org"

  gem "activerecord"
  gem "pg"
end

require "active_record"

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

# Get list of tables in the database
tables =
  ActiveRecord::Base
  .connection
  .execute("select * from pg_catalog.pg_tables where schemaname = 'public'")
  .pluck('tablename')

# 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})"
  Object.const_set(model, Class.new(ActiveRecord::Base))
end

# 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: "starters@wolfgangrittner.dev", first_name: "Wolfgang")