Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.turso.tech/llms.txt

Use this file to discover all available pages before exploring further.

This is currently in technical preview. Join us in Discord to report any issues.
In this Ruby quickstart we will learn how to:
  • Retrieve database credentials
  • Install the libSQL ActiveRecord gem
  • Connect to a local or remote Turso database
  • Define and create models
  • Perform basic CRUD operations
  • Execute raw SQL queries
  • Work with migrations
1

Retrieve database credentials

You will need an existing database to continue. If you don’t have one, create one.Get the database URL:
turso db show --url <database-name>
Get the database authentication token:
turso db tokens create <database-name>
Assign credentials to the environment variables inside .env.
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
2

Install

In your Ruby project, add the following gems to your Gemfile:
gem 'libsql_activerecord'
gem 'activerecord'
Then run:
bundle install
3

Connect

Create a Ruby file (e.g., database.rb) to set up the database connection:
require 'libsql_activerecord'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'libsql',
  url: ENV['TURSO_DATABASE_URL'],
  auth_token: ENV['TURSO_AUTH_TOKEN'],
  path: 'path/to/local/replica.db'
)
require 'libsql_activerecord'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'libsql',
  path: 'path/to/local.db'
)
require 'libsql_activerecord'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'libsql',
  url: ENV['TURSO_DATABASE_URL'],
  auth_token: ENV['TURSO_AUTH_TOKEN']
)
require 'libsql_activerecord'
require 'active_record'

ActiveRecord::Base.establish_connection(adapter: 'libsql')
4

Define models

Create model files for your database tables. For example, product.rb:
class Product < ActiveRecord::Base
  validates :name, presence: true
end
5

Create and execute a migration

Create a migration file (e.g., 001_create_products.rb):
class CreateProducts < ActiveRecord::Migration[8.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description
      t.timestamps
    end
  end
end
Execute the migration:
require_relative 'database'
require_relative '001_create_products'

CreateProducts.migrate(:up)
6

Execute

Perform some basic CRUD operations:
product = Product.create(name: 'Book', description: 'A book about books')
7

Work with associations

Define associations in your models:
class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end
Use associations in your code:
author = Author.create(name: 'Jane Doe')
book = author.books.create(title: 'My First Book')

puts author.books.count # => 1
puts book.author.name # => "Jane Doe"