ermi
ermi

Reputation: 1

How to seperate Admin and User database in Rails

I have devise gem in my application. I've been playing around with making some tables etc. Now I want to separate the database for the admin and the database for the user. I know its one single database. But, I'm not sure how to get it going in Rails.

Upvotes: 0

Views: 403

Answers (2)

Sikandar Tariq
Sikandar Tariq

Reputation: 1316

you can configure multiple databases in database.yml file

production:
  primary:
    database: my_primary_database
    user: root
    adapter: mysql
  secondary:
    database: my_secondary_database
    user: secondary_root
    adapter: mysql
    migrations_paths: db/secondary_migrate

and then in your modal, you can mention which database to use

class AnimalsBase < ApplicationRecord
  self.abstract_class = true
  connects_to database: { writing: :secondary }
end

checkout this link for more detail https://edgeguides.rubyonrails.org/active_record_multiple_databases.html

**For rails 4.2 - 5 ** you can use this gem Multiverse

P.S: Rails 6 is coming with a more neat solution for this, a stable build for rails 6 is now available you can upgrade to newer version too.

Upvotes: 2

ray
ray

Reputation: 5552

Rails have some limitation in which connecting only single database is major one. So I used to switch database using configuration setup in database.yml where you will have development & admin_development, (test & production etc. also)

You can get following constants,

ADMINCONFIG = YAML.load_file("#{Rails.root}/config/database.yml")['admin_development']

DEVCONFIG = YAML.load_file("#{Rails.root}/config/database.yml")['development']

And later whenever you need, you can switch from one to another as per requirement (through controller),

ActiveRecord::Base.connection(ADMINCONFIG)

Upvotes: 0

Related Questions