16

I am writing a payroll system that will integrate with a pre-existing system. The original system had a master database that handled user management and some global configuration, below that there are multiple databases each identical in structure, basically each database is one companies payroll database, all these are tied to the main database because it belongs to a parent company who has many subsidiaries each with their own HR department.

What I was wondering is if there is any way that I can, based on either a cookie or another method that stores what company they wish to connect to, dynamically change the ActiveRecord's target database based on their input using a before filter?

Here's an example:

User A logs in to the site, page loads with available companies that the user has permission to access, user will then select a company, they have admin privileges in that company, they add an employee, before that action is run, rails will switch the connection to the appropriate database then add the record.

1

2 Answers 2

12

You can use ActiveRecord::Base#establish_connection, to connect to the desired database.

You could pass the db credentials to establish_connection as a Hash

establish_connection(
  adapter: 'mysql2',
  encoding: 'utf8',
  pool: 5,
  username: 'me',
  password: 'mypassword'
)

There are more examples here

Sign up to request clarification or add additional context in comments.

4 Comments

Can you provide an example please?
Quick question, is the database.yml loaded when establish_connection called? because I might have to dynamically add new database connections via a web based control panel.
You can pass the db credentials to establish_connection as a Hash
okay sweet, this should work perfectly with what I'm going to be doing, thanks!
7

I'm not sure you can do it in run time, since the database connection is coupled to the class (model)

However, you can make different classes to be connected to different databases I don't want to copy someone else answer, so just look at this post

Connecting Rails 3.1 with Multiple Databases

and give him the credit

Good luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.