Connect to TiDB with 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.

Rails - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.

Prerequisites

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:

Run the sample app to connect to TiDB

This section demonstrates how to run the sample application code and connect to TiDB.

Step 1: Clone the sample app repository

Run the following commands in your terminal window to clone the sample code repository:

  1. git clone https://github.com/tidb-samples/tidb-ruby-rails-quickstart.git
  2. cd tidb-ruby-rails-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including mysql2 and dotenv) for the sample app:

  1. bundle install

Install dependencies for existing projects

For your existing project, run the following command to install the packages:

  1. bundle add mysql2 dotenv

Step 3: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you’ve selected.

  • TiDB Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. In the connection dialog, select Rails from the Connect With drop-down list and keep the default setting of the Endpoint Type as Public.

  4. If you have not set a password yet, click Generate Password to generate a random password.

  5. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  6. Edit the .env file, set up the DATABASE_URL environment variable as follows, and copy the connection string from the connection dialog as the variable value.

    1. DATABASE_URL='mysql2://{user}:{password}@{host}:{port}/{database_name}?ssl_mode=verify_identity'

    Rails - 图2

    Note

    For TiDB Serverless, TLS connection MUST be enabled with the ssl_mode=verify_identity query parameter when using public endpoint.

  7. Save the .env file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  9. Click Connect in the upper-right corner. A connection dialog is displayed.

  10. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

  11. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  12. Edit the .env file, set up the DATABASE_URL environment variable as follows, copy the connection string from the connection dialog as the variable value, and set the sslca query parameter to the file path of the CA certificate downloaded from the connection dialog:

    1. DATABASE_URL='mysql2://{user}:{password}@{host}:{port}/{database}?ssl_mode=verify_identity&sslca=/path/to/ca.pem'

    Rails - 图3

    Note

    It is recommended to enable TLS connection when using the public endpoint to connect to TiDB Dedicated.

    To enable TLS connection, modify the value of the ssl_mode query parameter to verify_identity and the value of sslca to the file path of CA certificate downloaded from the connection dialog.

  13. Save the .env file.

  14. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  15. Edit the .env file, set up the DATABASE_URL environment variable as follows, and replace the {user}, {password}, {host}, {port}, and {database} with your own TiDB connection information:

    1. 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.

  16. Save the .env file.

Step 4: Run the code and check the result

  1. Create the database and table:

    1. bundle exec rails db:create
    2. bundle exec rails db:migrate
  2. Seed the sample data:

    1. bundle exec rails db:seed
  3. Run the following command to execute the sample code:

    1. bundle exec rails runner ./quickstart.rb

If the connection is successful, the console will output the version of the TiDB cluster as follows:

  1. 🔌 Connected to TiDB cluster! (TiDB version: 8.0.11-TiDB-v8.1.0)
  2. Loading sample game data...
  3. Loaded sample game data.
  4. 🆕 Created a new player with ID 12.
  5. ℹ️ Got Player 12: Player { id: 12, coins: 100, goods: 100 }
  6. 🔢 Added 50 coins and 50 goods to player 12, updated 1 row.
  7. 🚮 Deleted 1 player data.

Sample code snippets

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.

Connect to TiDB with connection options

The following code in config/database.yml establishes a connection to TiDB with options defined in the environment variables:

  1. default: &default
  2. adapter: mysql2
  3. encoding: utf8mb4
  4. pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  5. url: <%= ENV["DATABASE_URL"] %>
  6. development:
  7. <<: *default
  8. test:
  9. <<: *default
  10. database: quickstart_test
  11. production:
  12. <<: *default

Rails - 图4

Note

For TiDB Serverless, TLS connection MUST be enabled via setting the ssl_mode query parameter to verify_identity in DATABASE_URL when using public endpoint, but you don’t have to specify an SSL CA certificate via DATABASE_URL, because mysql2 gem will search for existing CA certificates in a particular order until a file is discovered.

Insert data

The following query creates a single Player with two fields and returns the created Player object:

  1. new_player = Player.create!(coins: 100, goods: 100)

For more information, refer to Insert data.

Query data

The following query returns the record of a specific player by ID:

  1. player = Player.find_by(id: new_player.id)

For more information, refer to Query data.

Update data

The following query updates a Player object:

  1. player.update(coins: 50, goods: 50)

For more information, refer to Update data.

Delete data

The following query deletes a Player object:

  1. player.destroy

For more information, refer to Delete data.

Best practices

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.

  1. /etc/ssl/certs/ca-certificates.crt # Debian / Ubuntu / Gentoo / Arch / Slackware
  2. /etc/pki/tls/certs/ca-bundle.crt # RedHat / Fedora / CentOS / Mageia / Vercel / Netlify
  3. /etc/ssl/ca-bundle.pem # OpenSUSE
  4. /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.

Next steps

Need help?

Ask questions on the Discord channel.