Connect to both postgresql and mongodb in the same Rails app

Post by Lưu Đại at 15-11-2023
I use NoSQL in my project when I need to save log of requests or have monthly / weekly / daily reports that requires pull data from multiple tables and saves it to separated database or tracks the histories of some important records. In short, whenever I deal with data with no structure or read / write heavy. 

1. Create a Rails project as normal and config connect to postgresql

2. Add gem mongoid to the gemfile and create mongoid.yml file

development:
  clients:
    default:
      database: multidb_development
      hosts:
        - localhost:27017
      options:
        server_selection_timeout: 1

test:
  clients:
    default:
      database: multidb_test
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 1
config/mongoid.yml 

3. Create a model (not inherited from ApplicationRecord)

class Log
  include Mongoid::Document
  include Mongoid::Timestamps # auto generate created_at, updated_at when create / update record

  field :controller, type: String
  field :action, type: String
end
app/models/log.rb

4. Test it

class ApplicationController < ActionController::Base
  before_action :write_log

  def write_log
    # Store log in mongo db
    Log.create(controller: controller_name, action: action_name)
  end
end

5. Code example
- https://github.com/LuuDai-bit/multidb