Turso Adds Ruby on Rails Support

Levy AlbuquerqueLevy Albuquerque
Jamie BartonJamie Barton
Cover image for Turso Adds Ruby on Rails Support

Embedding databases directly alongside your application code means you can eliminate the network latency that traditionally exists between your app and database, impacting performance.

In October, we announced the Ruby SDK, and today we are excited to announce the first technical preview of the Rubygem for ActiveRecord that supports Rails.

#Getting Started

Adding Turso to your Rails application takes just a few steps.

First add the libsql_activerecord gem to your Gemfile:

bundle add 'libsql_activerecord'

Update your config/database.yml with your Turso database url and auth_token:

default: &default
  adapter: libsql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  url: <%= ENV['TURSO_DATABASE_URL'] %>
  auth_token: <%= ENV['TURSO_AUTH_TOKEN'] %>
  path: 'path/to/local/replica.db'

The path property here points to a file that will be used to sync the remote database locally, so you can work offline, and eliminate network latency.

Next, update .env.development with the following:

TURSO_DATABASE_URL=libsql://…
TURSO_AUTH_TOKEN=...

Learn more about embedded replicas, and how to set up your local replica to avoid network latency.

That’s it! Your Rails application is now ready to use Turso.

#Running migrations

Use the rails generator to scaffold a simple CRUD UI for testing everything works:

rails g scaffold Post name:string title:string content:text

This scaffold will generate an ActiveRecord migration inside the folder db/migrate with the following:

class CreatePosts < ActiveRecord::Migration[8.0]
  def change
    create_table :posts do |t|
      t.string :name
      t.string :title
      t.text :content

      t.timestamps
    end
  end
end

You can apply this migration to the database using the following command:

bin/rails db:migrate

Now when we start the server:

bin/rails server

You should now be able to create, update, and destroy Posts at: http://127.0.0.1:3000:

You can try this yourself and view the source code on GitHub.

#Beyond Rails

The libsql_activerecord adapter works with any Ruby application using ActiveRecord, not just Rails. Let's explore some raw ActiveRecord usage examples.

#Connecting to the Database

For a standalone Ruby application, you can establish a connection like this:

require 'libsql_activerecord'
require 'active_record'

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

#Defining Models

Create model classes that inherit from ActiveRecord::Base:

class Product < ActiveRecord::Base
  validates :name, presence: true
end

#Creating and Executing Migrations

You can define and run migrations programmatically:

class CreateProducts < ActiveRecord::Migration[8.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description
      t.timestamps
    end
  end
end

CreateProducts.migrate(:up)

#Performing CRUD Operations

Here are examples of basic CRUD operations:

# Create
product = Product.create(name: 'Book', description: 'A book about books')

# Read
all_products = Product.all
first_product = Product.first
found_product = Product.find_by(name: 'Book')

# Update
product.update(description: 'An updated description')

# Delete
product.destroy

#Executing Raw SQL Queries

You can execute raw SQL queries when needed:

results = ActiveRecord::Base.connection.execute("SELECT * FROM products WHERE name LIKE '%Book%'")

results.each do |row|
  puts row.inspect
end

#Working with Associations

ActiveRecord makes it easy to work with database relationships:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

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"

#For Sinatra Users

If you're using Sinatra, the setup is just as straightforward:

require 'sinatra'
require 'libsql-activerecord'
require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'libsql',
  url: ENV['DATABASE_URL'],
  auth_token: ENV['AUTH_TOKEN']
)

get '/products' do
  Product.all.to_json
end

#Learn More

Ready to get started? Check out the Rubygem, and source code for further details.

The flexibility of ActiveRecord with Turso allows you to build powerful applications with ease, whether you're using Rails, Sinatra, or a custom Ruby setup.

scarf