title | summary | toc | referral_id | filter_category | filter_html | filter_sort | docs_area | |
---|---|---|---|---|---|---|---|---|
Build a Ruby App with CockroachDB and the Ruby pg Driver |
Learn how to use CockroachDB from a simple Ruby application with the pg client driver. |
true |
false |
docs_ruby_pg |
crud_ruby |
Use <strong>pg</strong> |
1 |
get_started |
{% include filter-tabs.md %}
This tutorial shows you how build a simple Ruby application with CockroachDB and the Ruby pg driver.
{% include {{ page.version.version }}/setup/sample-setup-certs.md %}
Clone the code's GitHub repository.
{% include_cached copy-clipboard.html %}
git clone https://github.com/cockroachlabs/hello-world-ruby-pg
The code connects as the user you created and executes some basic SQL statements: creating a table, inserting rows, and reading and printing the rows.
-
Install
libpq
for your platform.For example, to install
libpq
on macOS with Homebrew, run the following command:{% include_cached copy-clipboard.html %}
brew install libpq
-
Configure
bundle
to uselibpq
.For example, if you installed
libpq
on macOS with Homebrew, run the following command from thehello-world-ruby-pg
directory:{% include_cached copy-clipboard.html %}
bundle config --local build.pg --with-opt-dir="{libpq-path}"
Where
{libpq-path}
is the full path to thelibpq
installation on your machine (e.g.,/usr/local/opt/libpq
). -
Install the dependencies:
{% include_cached copy-clipboard.html %}
bundle install
-
Set the
DATABASE_URL
environment variable to the connection string to your {{ site.data.products.db }} cluster:{% include_cached copy-clipboard.html %}
$ export DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable"
{% include_cached copy-clipboard.html %}
$ export DATABASE_URL="{connection-string}"
Where
{connection-string}
is the connection string you copied earlier.The app uses the connection string saved to the
DATABASE_URL
environment variable to connect to your cluster and execute the code. -
Run the code to create a table and insert some rows:
{% include_cached copy-clipboard.html %}
ruby main.rb
The output should look similar to the following:
------------------------------------------------ print_balances(): Balances as of '2021-02-23 11:56:54 -0800': {"id"=>"1", "balance"=>"1000"} {"id"=>"2", "balance"=>"250"} ------------------------------------------------ transfer_funds(): Trying to transfer 100 from account 1 to account 2 ------------------------------------------------ print_balances(): Balances as of '2021-02-23 11:56:55 -0800': {"id"=>"1", "balance"=>"900"} {"id"=>"2", "balance"=>"350"}
Read more about using the Ruby pg driver.
{% include {{page.version.version}}/app/see-also-links.md %}