Gabriel Carneiro
Gabriel Carneiro

Reputation: 85

How to connect to an existing database in Ruby on Rails

I have a table named User at my project and I want to access another database of an another existing project. The database that I want to access it makes part of a project that I need to conceed access to my table User. The reason is that my table User that is responsable to authenticate an user base, and after their authentication they will return a token and so they can access the another database. The database.yml of my table User is configured like this :

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

The database of the another project that I want to access is configured as follows :

default: &default
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_bin
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  variables:
    sql_mode: TRADITIONAL

development:
  <<: *default
  username: root
  password:
  database: <company_name>dev

test:
  <<: *default
  database: <company_name>_test
  username: root
  password:

production:
  <<: *default
  database: <%= ENV['RDS_DB_NAME'] %>
  username: <%= ENV['RDS_USERNAME'] %>
  password: <%= ENV['RDS_PASSWORD'] %>
  host: <%= ENV['RDS_HOSTNAME'] %>
  port: <%= ENV['RDS_PORT'] %>

How can I solve this problem ?

Upvotes: 1

Views: 757

Answers (1)

rmhunter
rmhunter

Reputation: 581

You can add another database to the first config (adjust as needed, I just copied your config from the second):

...

other:
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_bin
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  variables:
    sql_mode: TRADITIONAL
  database: <%= ENV['RDS_DB_NAME'] %>
  username: <%= ENV['RDS_USERNAME'] %>
  password: <%= ENV['RDS_PASSWORD'] %>
  host: <%= ENV['RDS_HOSTNAME'] %>
  port: <%= ENV['RDS_PORT'] %>

You can then create a subfolder in your app/models directory to give you ActiveRecord access to the other database. First create a base class:

# app/models/other/base.rb

module Other
  class Base < ActiveRecord::Base
    establish_connection configurations['other']
    self.abstract_class = true
  end
end

Then add a User model within that module:

# app/models/other/user.rb

module Other
  class User < Base
    self.table_name = 'users'
    self.primary_key = 'id'
  end
end

Now, you can refer to the "other" User table like this:

Other::User.find(other_user_id)

Also keep in mind you will need to install the mysql2 database adapter in your first project's Gemfile.

Also note that you'll probably want a better name/module than "Other", I just used that as the example here.

Upvotes: 1

Related Questions