title | summary | toc | |
---|---|---|---|
Build a Ruby App with CockroachDB |
Learn how to use CockroachDB from a simple Ruby application with the ActiveRecord ORM. |
true |
false |
This tutorial shows you how build a simple Ruby application with CockroachDB using a PostgreSQL-compatible driver or ORM. We've tested and can recommend the Ruby pg driver and the ActiveRecord ORM, so those are featured here.
{{site.data.alerts.callout_success}}For a more realistic use of ActiveRecord with CockroachDB, see our examples-orms
repository.{{site.data.alerts.end}}
Make sure you have already installed CockroachDB.
To install ActiveRecord as well as the pg driver and a CockroachDB Ruby package that accounts for some minor differences between CockroachDB and PostgreSQL, run the following command:
{% include copy-clipboard.html %}
$ gem install activerecord pg activerecord-cockroachdb-adapter
{% include {{ page.version.version }}/app/common-steps.md %}
The following code uses the ActiveRecord ORM to map Ruby-specific objects to SQL operations. Specifically, Schema.new.change()
creates an accounts
table based on the Account model (or drops and recreates the table if it already exists), Account.create()
inserts rows into the table, and Account.all
selects from the table so that balances can be printed.
Copy the code or download it directly.
{% include copy-clipboard.html %}
{% include {{ page.version.version }}/app/activerecord-basic-sample.rb %}
Then run the code:
{% include copy-clipboard.html %}
$ ruby activerecord-basic-sample.rb
The output should be:
-- create_table(:accounts, {:force=>true})
-> 0.0361s
1 1000
2 250
To verify that the table and rows were created successfully, you can again use the built-in SQL client:
{% include copy-clipboard.html %}
$ cockroach sql --insecure -e 'SHOW TABLES' --database=bank
+----------+
| Table |
+----------+
| accounts |
+----------+
(1 row)
{% include copy-clipboard.html %}
$ cockroach sql --insecure -e 'SELECT id, balance FROM accounts' --database=bank
+----+---------+
| id | balance |
+----+---------+
| 1 | 1000 |
| 2 | 250 |
+----+---------+
(2 rows)
Read more about using the ActiveRecord ORM, or check out a more realistic implementation of ActiveRecord with CockroachDB in our examples-orms
repository.
You might also be interested in using a local cluster to explore the following core CockroachDB features: