Skip to content

Ruby: Rails Active Record

Defines the schema with Active Record migrations DSL and uses a model. In a Rails application the same change is DATABASE_URL (or host: in config/database.yml). The code is the same against the original database and against MachSQL; only the address changes.

DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/app
DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • Ruby 4.0
  • activerecord 8.1.4 (Rails 8.1)
  • pg 1.7.0
Terminal window
bundle install
export DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app
bundle exec ruby main.rb

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

main.rb
# Active Record (Rails 8.1) outside a Rails application.
require "active_record"
ActiveRecord::Base.establish_connection(ENV.fetch("DATABASE_URL"))
unless ActiveRecord::Base.connection.table_exists?(:ar_todos)
ActiveRecord::Schema.define do
create_table :ar_todos do |t|
t.string :title, null: false
t.boolean :done, null: false, default: false
end
end
end
class Todo < ActiveRecord::Base
self.table_name = "ar_todos"
end
todo = Todo.create!(title: "write the examples")
puts "inserted todo #{todo.id}, #{Todo.where(done: false).count} open"
Gemfile
source "https://rubygems.org"
gem "activerecord", "8.1.4"
gem "pg", "1.7.0"