change database for each user

0

I am developing a multi-company website in which each company has its database and when the user logs in, he will then access the database of the company he is associated with, each user having a record called "empresa .id. " The problem comes when a user of an "X" company starts a session and then another user of a company "Y" also logs in, making it possible to change the database for the whole system, thanks to this last user of the company "Y" also for the user of the company "X" and all other users instead of each user making use of a specific database without being affected by the database of other users.

This is my code to change the database (I use the in applicationController):

before_action :set_database

def set_database
   if usuario_signed_in?
      empresa = (current_usuario.empresa_id).to_s.to_sym 
      ActiveRecord::Base.establish_connection(empresa)
    else
      ActiveRecord::Base.establish_connection(:'232')
    end
 end

The variable "company" will take the value of "company_id" of the user and make the connection with the database of the company, for example "company" has a value "32" then it will make the connection in database.yml with :

'32':
  adapter: sqlserver
  mode: dblib
  dataserver:
  host: host
  port: 1433
  database: database
  username: user
  password: pass
  timeout: 60000
  azure: true

How can I log in with several users without affecting others who have a different database?

    
asked by jeff 13.04.2017 в 15:36
source

2 answers

1

Good morning

First of all, apologies, I know that it is not the solution to your question, although maybe it is your problem.

Why do not you consider using the same database for all users?

That is, when identifying the user identify the company thereof, for example Name: Macupo Company: LAM

Then, you just have to add one more column to each table to distinguish the companies. For example TAB_CODEMP = LAM.

I think it would greatly simplify the development you intend to carry out (in exchange for, in anticipation of the future, having tables with more fields to satisfy the different requirements).

Greetings

    
answered by 13.04.2017 в 15:41
0

The gem Apartment is in charge of doing what you are looking for. The architecture you want is called MultiTenancy.

link

Suppose your application has a product table. With apartment you will be able to select between the three possible Tenancy types:

  • Use a single table of products with a column (for example) empresa_id that will distinguish which company the product belongs to.
  • Use the same database, but with different Schemas for each company.
  • Use a different database for each company.

I hope it will help you to continue investigating and find what you are looking for!

Here is a Screencast where they explain how to configure and use Apartment link

    
answered by 21.04.2017 в 16:47