Ruby on Railsは、Ruby言語で開発されたフルスタックのWebアプリケーションフレームワークであり、ORMコンポーネントとしてActiveRecordを組み込んでいます。ActiveRecordは以下の特徴を提供します:
- 惯例に基づくオブジェクト関係マッピング(ORM)
- モデルの関連付けと継承をサポート
- クエリインターフェースを提供し、複雑なデータベースクエリを構築可能
- データベースマイグレーションをサポート
- 組み込みのバリデーションとコールバックメカニズム
本記事では、Ruby on RailsのActiveRecordを使用してOceanBaseデータベースに接続し、テーブルの作成、データの挿入、更新、クエリなどの基本的なデータベース操作を実装する方法を紹介します。
前提条件
- Ruby 3.2.1以降のバージョンがインストールされていること。
- Rails 6.0以降のバージョンがインストールされていること。
- OceanBaseデータベースをインストール済みで、MySQLテナントが作成されていること。
- OceanBaseデータベースの接続文字列を取得していること。
手順
- OceanBaseデータベースの接続文字列を取得します。
- RubyとRailsをインストールします。
- Railsアプリケーションを作成し、データベース接続を設定します。
- モデルを作成し、基本的なCRUD操作を実装します。
- プログラムを実行し、結果を検証します。
ステップ1:OceanBaseデータベースの接続文字列を取得する
OceanBaseデータベースのデプロイ担当者または管理者から、該当するデータベース接続文字列を取得します。
obclient -h$host -P$port -u$user_name -p$password -D$database_name
パラメータ説明:
$host:OceanBaseデータベースへの接続IPアドレス。OceanBaseデータベースプロキシ(OceanBase Database Proxy、ODP)接続方式ではODPアドレスを使用し、直接接続方式ではOBServerノードのIPアドレスを使用します。$port:OceanBaseデータベースへの接続ポート。ODP接続方式のデフォルトポートは2883で、ODPデプロイ時にカスタマイズ可能です。直接接続方式のデフォルトポートは2881で、OceanBaseデータベースのデプロイ時にカスタマイズ可能です。$database_name:アクセス対象のデータベース名。注意
テナントに接続するユーザーは、データベースに対する
CREATE、INSERT、UPDATE、およびSELECT権限が付与されていなければなりません。その他のユーザー権限の詳細については、MySQLモードの権限分類を参照してください。$user_name:テナントの接続アカウント。ODP接続の一般的な形式:ユーザー名@テナント名#クラスタ名またはクラスタ名:テナント名:ユーザー名。直接接続方式の形式:ユーザー名@テナント名。$password:アカウントのパスワード。
その他の接続文字列の情報については、OBClientを使用したOceanBaseテナントへの接続を参照してください。
例:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest
ステップ2:RubyとRailsのインストール
RubyとRailsをインストールします:
# 依存関係のインストール apt install -y curl vim git build-essential libmysqlclient-dev libssl-dev # RVMのインストール curl -L https://raw.githubusercontent.com/wayneeseguin/rvm/master/binscripts/rvm-installer | bash -s stable # RVM環境のロード source /usr/local/rvm/src/rvm/scripts/rvm # RVMがRubyをダウンロードするリポジトリをRuby Chinaのミラーに変更 echo "ruby_url=https://guides.rubyonrails.org/active_record_basics.html" > /usr/local/rvm/src/rvm/config/db # RVMの依存関係のインストール rvm requirements # 必要なディレクトリの作成 mkdir -p /usr/local/rvm/src/rvm/rubies mkdir -p /usr/local/rvm/src/rvm/archives mkdir -p /usr/local/rvm/src/rvm/src/ruby-3.2.1 # Ruby 3.2.1のインストール rvm install 3.2.1 rvm use 3.2.1 --default # BundlerとRailsのインストール gem install bundler gem install rails # インストールの確認 rails -v # MySQL2のインストール gem install mysql2 -v '0.5.6'新しいRailsアプリケーションを作成します:
# 新しいRailsアプリケーションを作成し、テストフレームワークをスキップする rails new oceanbase_rails --skip-test cd oceanbase_railsGemfileファイルを修正し、tzinfo-dataが含まれていることを確認します:
gem 'tzinfo-data', platforms: [:ruby]依存関係をインストールします:
bundle install
ステップ3:モデルを作成し、CRUD操作を実装する
ユーザーモデル
app/models/user.rbを作成します:class User < ApplicationRecord validates :username, presence: true validates :email, presence: true, uniqueness: true validates :age, numericality: { only_integer: true, allow_nil: true } endコントローラー
app/controllers/users_controller.rbを作成し、CRUD操作を実装します:class UsersController < ApplicationController # すべてのユーザーを取得する def index @users = User.all render json: @users end # 一時的にCSRF認証を無効にする skip_before_action :verify_authenticity_token, if: :json_request? # 新規ユーザーを作成する def create @user = User.new(user_params) if @user.save render json: @user, status: :created else render json: @user.errors, status: :unprocessable_entity end end # 単一ユーザーを取得する def show @user = User.find(params[:id]) render json: @user rescue ActiveRecord::RecordNotFound render json: { error: 'User not found' }, status: :not_found end # ユーザー情報を更新する def update @user = User.find(params[:id]) if @user.update(user_params) render json: @user else render json: @user.errors, status: :unprocessable_entity end end def json_request? request.format.json? end private def user_params params.require(:user).permit(:username, :email, :age) end endルートを設定し、
config/routes.rbを編集します:Rails.application.routes.draw do resources :users end
ステップ4:APIをテストする
Railsサーバーを起動します:
rails server -p 3000curlまたはPostmanを使用してAPIをテストします:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -H "Accept: application/json" -d '{"user": {"username":"testuser","email":"test@example.com","age":25}}' curl -X PATCH http://localhost:3000/users/1 \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -d '{"user": {"age":26}}' curl -X DELETE http://localhost:3000/users/1 -H "Content-Type: application/json" -H "Accept: application/json"