Cassandra Example Using Rails
The purpose of this step-by-step tutorial is to provide a very simple example of configuring and using the Cassandra database engine with the Ruby Language.
Docker Desktop 4.23.0 or newer
Rails >= 5.2.8.1 and < 6
Ruby >= 2.7.8 and < 3
Note: This tutorial was updated on macOS 13.5.2.
Open new terminal window
Create the project directory
mkdir blog
cd blog
Create docker-compose.yml
file with the following content:
services:
some-cassandra:
image: cassandra:4.1.3
container_name: some-cassandra
environment:
- CASSANDRA_CLUSTER_NAME=cassandra-cluster
ports:
- 9042:9042
volumes:
- cassandra-data:/var/lib/cassandra
volumes:
cassandra-data: {}
Start a single node cluster
docker-compose up -d
Check the status of your cluster
docker-compose exec some-cassandra nodetool status
Note: One should see that the node status as Up Normal (UN) that looks similar to the following:
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns Host ID Rack
UN 172.19.0.2 582.5 KB 256 ? e61cf276-c860-4990-bf03-37161414aed2 rack1
Note: Non-system keyspaces don't have the same replication settings, effective ownership information is meaningless
Generate a new Rails application
gem install rails -v '5.2.8.1'
rails _5.2.8.1_ new . ---skip-active-record --skip-active-storage -T --skip-bundle --skip-webpack-install --skip-javascript --no-rc
Add the Ruby cequel gem
bundle add i18n --version "= 1.8.11"
bundle add cequel
bundle add activemodel-serializers-xml
Generate scaffold of the application
rails g scaffold post title body
Add the following as the first route within config/routes.rb file:
root 'posts#index'
Create app/models/post.rb file with the following content:
class Post
include Cequel::Record
key :id, :timeuuid, auto: true
column :title, :text
column :body, :text
timestamps
end
Create a default Cassandra configuration file
rails g cequel:configuration
Initialize Cassandra keyspace (database)
rails cequel
create
Synchronize your Rails model schemas with Cassandra keyspace
rails cequel:migrate
Start the Rails server
rails s
Play with the application
open http://localhost:3000
Remove the keyspace
rails cequel
drop
Stop a single node cluster
docker-compose down
Bug reports and feature requests can be filed for the cassandra-example-using-rails project here:
Follow Conrad Taylor on Twitter (@conradwt)
This repository is released under the MIT License.
© Copyright 2014 - 2023 Conrad Taylor. All Rights Reserved.