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.
The only change
Section titled “The only change”DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/appDATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appNothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- Ruby 4.0
- activerecord 8.1.4 (Rails 8.1)
- pg 1.7.0
bundle installexport DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appbundle exec ruby main.rbExpected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
# 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 endend
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"source "https://rubygems.org"
gem "activerecord", "8.1.4"gem "pg", "1.7.0"