跳至正文內容
TursoDB.cn 獨立社群 · MVCC 並行寫入與每 Agent 獨立庫實戰 閱讀解析 →
Turso Cloud SDK 開發套件 官方 SDK ActiveRecord 實戰指南

Ruby on Rails + Turso

在幾分鐘內於你的 Ruby on Rails 專案中設定好 Turso。

WARNING

此功能目前處於技術預覽階段。若有任何問題,請加入我們的 Discord 回報。

先決條件

在開始之前,請確認你已經:

1. 安裝 libsql_activerecord Rubygem

將以下內容加入你的 Gemfile:

gem 'libsql_activerecord'

然後執行:

bundle install

2. 設定資料庫認證資訊

取得資料庫 URL:

turso db show --url <database-name>

取得資料庫認證權杖:

turso db tokens create <database-name>

將認證資訊指定給 .env 中的環境變數。

TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=

將你的 Turso 認證資訊加入 Rails 的 credentials 檔案或環境變數。

3. 使用 libsql 轉接器

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: storage/development.sqlite3 # For embedded replica

4. 建立並執行遷移

產生一個遷移:

rails generate migration CreateProducts name:string description:text

執行遷移:

rails db:migrate

5. 定義模型

在 app/models/product.rb 中建立一個模型:

class Product < ApplicationRecord
  validates :name, presence: true
end

6. 在控制器中使用

在你的控制器中,你現在可以使用 ActiveRecord 方法與你的 Turso 資料庫互動:

class ProductsController < ApplicationController
  def index
    @products = Product.all
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to @product, notice: 'Product was successfully created.'
    else
      render :new
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :description)
  end
end

7. 執行原始 SQL(如有需要)

你也可以執行原始 SQL 查詢:

results = ActiveRecord::Base.connection.execute("SELECT * FROM products")

範例

同步自官方 Turso 文件倉庫 ( tursodatabase/turso-docs · MIT 開源授權) 檢視官方原文 ↗
搜尋
按 Esc 關閉 · 由 Pagefind 靜態索引驅動