title | summary |
---|---|
Connect to TiDB with Rails framework and ActiveRecord ORM |
Learn how to connect to TiDB using the Rails framework. This tutorial gives Ruby sample code snippets that work with TiDB using the Rails framework and ActiveRecord ORM. |
TiDB is a MySQL-compatible database, Rails is a popular web application framework written in Ruby, and ActiveRecord ORM is the object-relational mapping in Rails.
In this tutorial, you can learn how to use TiDB and Rails to accomplish the following tasks:
- Set up your environment.
- Connect to your TiDB cluster using Rails.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations using ActiveRecord ORM.
Note:
This tutorial works with TiDB Cloud Serverless, TiDB Cloud Dedicated, and TiDB Self-Managed.
To complete this tutorial, you need:
- Ruby >= 3.0 installed on your machine
- Bundler installed on your machine
- Git installed on your machine
- A TiDB cluster running
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Cloud Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
- (Recommended) Follow Creating a TiDB Cloud Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
This section demonstrates how to run the sample application code and connect to TiDB.
Run the following commands in your terminal window to clone the sample code repository:
git clone https://github.com/tidb-samples/tidb-ruby-rails-quickstart.git
cd tidb-ruby-rails-quickstart
Run the following command to install the required packages (including mysql2
and dotenv
) for the sample app:
bundle install
Install dependencies for existing projects
For your existing project, run the following command to install the packages:
bundle add mysql2 dotenv
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
-
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
-
Click Connect in the upper-right corner. A connection dialog is displayed.
-
In the connection dialog, select
Rails
from the Connect With drop-down list and keep the default setting of the Connection Type asPublic
. -
If you have not set a password yet, click Generate Password to generate a random password.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up theDATABASE_URL
environment variable as follows, and copy the connection string from the connection dialog as the variable value.DATABASE_URL='mysql2://{user}:{password}@{host}:{port}/{database_name}?ssl_mode=verify_identity'
Note
For TiDB Cloud Serverless, TLS connection MUST be enabled with the
ssl_mode=verify_identity
query parameter when using public endpoint. -
Save the
.env
file.
-
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
-
Click Connect in the upper-right corner. A connection dialog is displayed.
-
In the connection dialog, select Public from the Connection Type drop-down list, and then click CA cert to download the CA certificate.
If you have not configured the IP access list, click Configure IP Access List or follow the steps in Configure an IP Access List to configure it before your first connection.
In addition to the Public connection type, TiDB Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up theDATABASE_URL
environment variable as follows, copy the connection string from the connection dialog as the variable value, and set thesslca
query parameter to the file path of the CA certificate downloaded from the connection dialog:DATABASE_URL='mysql2://{user}:{password}@{host}:{port}/{database}?ssl_mode=verify_identity&sslca=/path/to/ca.pem'
Note
It is recommended to enable TLS connection when using the public endpoint to connect to TiDB Cloud Dedicated.
To enable TLS connection, modify the value of the
ssl_mode
query parameter toverify_identity
and the value ofsslca
to the file path of CA certificate downloaded from the connection dialog. -
Save the
.env
file.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up theDATABASE_URL
environment variable as follows, and replace the{user}
,{password}
,{host}
,{port}
, and{database}
with your own TiDB connection information:DATABASE_URL='mysql2://{user}:{password}@{host}:{port}/{database}'
If you are running TiDB locally, the default host address is
127.0.0.1
, and the password is empty. -
Save the
.env
file.
-
Create the database and table:
bundle exec rails db:create bundle exec rails db:migrate
-
Seed the sample data:
bundle exec rails db:seed
-
Run the following command to execute the sample code:
bundle exec rails runner ./quickstart.rb
If the connection is successful, the console will output the version of the TiDB cluster as follows:
🔌 Connected to TiDB cluster! (TiDB version: 8.0.11-TiDB-v8.5.0)
⏳ Loading sample game data...
✅ Loaded sample game data.
🆕 Created a new player with ID 12.
ℹ️ Got Player 12: Player { id: 12, coins: 100, goods: 100 }
🔢 Added 50 coins and 50 goods to player 12, updated 1 row.
🚮 Deleted 1 player data.
You can refer to the following sample code snippets to complete your own application development.
For complete sample code and how to run it, check out the tidb-samples/tidb-ruby-rails-quickstart repository.
The following code in config/database.yml
establishes a connection to TiDB with options defined in the environment variables:
default: &default
adapter: mysql2
encoding: utf8mb4
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
url: <%= ENV["DATABASE_URL"] %>
development:
<<: *default
test:
<<: *default
database: quickstart_test
production:
<<: *default
Note
For TiDB Cloud Serverless, TLS connection MUST be enabled via setting the
ssl_mode
query parameter toverify_identity
inDATABASE_URL
when using public endpoint, but you don't have to specify an SSL CA certificate viaDATABASE_URL
, because mysql2 gem will search for existing CA certificates in a particular order until a file is discovered.
The following query creates a single Player with two fields and returns the created Player
object:
new_player = Player.create!(coins: 100, goods: 100)
For more information, refer to Insert data.
The following query returns the record of a specific player by ID:
player = Player.find_by(id: new_player.id)
For more information, refer to Query data.
The following query updates a Player
object:
player.update(coins: 50, goods: 50)
For more information, refer to Update data.
The following query deletes a Player
object:
player.destroy
For more information, refer to Delete data.
By default, the mysql2 gem (used by ActiveRecord ORM to connect TiDB) will search for existing CA certificates in a particular order until a file is discovered.
- /etc/ssl/certs/ca-certificates.crt # Debian / Ubuntu / Gentoo / Arch / Slackware
- /etc/pki/tls/certs/ca-bundle.crt # RedHat / Fedora / CentOS / Mageia / Vercel / Netlify
- /etc/ssl/ca-bundle.pem # OpenSUSE
- /etc/ssl/cert.pem # MacOS / Alpine (docker container)
While it is possible to specify the CA certificate path manually, this approach may cause significant inconvenience in multi-environment deployment scenarios, as different machines and environments may store the CA certificate in varying locations. Therefore, setting sslca
to nil
is recommended for flexibility and ease of deployment across different environments.
- Learn more usage of ActiveRecord ORM from the documentation of ActiveRecord.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as: Insert data, Update data, Delete data, Query data, Transactions, and SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Ask the community on Discord or Slack, or submit a support ticket.
Ask the community on Discord or Slack, or submit a support ticket.