Skip to content

Instantly share code, notes, and snippets.

@barelyknown
Last active February 18, 2019 23:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barelyknown/9754744 to your computer and use it in GitHub Desktop.
Save barelyknown/9754744 to your computer and use it in GitHub Desktop.
Simple solution to use a follower database for some ActiveRecord reads.

Heroku recommends using Octopus to connect to followers.

But, Octopus doesn't work yet with Rails 4.1.

Here's a super simple solution to use a follower for some reads for an ActiveRecord class:

config/database.yml

follower_development:
  <<: *default
  database: your_database_name_development

follower_test:
  <<: *default
  database: your_database_name_test

follower_production:
  url: <%= ENV["YOUR_FOLLOWER_DATABASE_URL"] %>

app/models/concerns/follower.rb

module Follower
  extend ActiveSupport::Concern

  included do
    self.const_set "Follower", Class.new(self)
    class self::Follower
      establish_connection "follower_#{Rails.env}".to_sym
    end
  end

end

app/models/example.rb

class Example < ActiveRecord::Base
  include Follower
end
irb(main):> Example.count
=> 1

irb(main):> Example::Follower.count
=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment