Dynamic database connections

class ApplicationController < ActionController::Base

private

def message_databaser
Message.establish_connection(
:host     => current_user.database.host,
:username => current_user.database.username,
:password => current_user.database.password,
:database => current_user.database.database
)
end

def friend_databaser
Message.establish_connection(
:host     => current_user.database.host,
:username => current_user.database.username,
:password => current_user.database.password,
:database => current_user.database.database
)
end

end



class MessagesController < ApplicationController
before_filter :message_databaser

def index
@messages = Message.all     
end


end



class FriendsController < ApplicationController
before_filter :friend_databaser

def index
@friends = Friends.all      
end

end

Some models use other databases, which depend on the current user. Now I want to clear this code a bit. I want to write a method like this:

def databaser(model_name, user)
model_name.establish_connection(
:host     => user.database.host,
:username => user.database.username,
:password => user.database.password,
:database => user.database.database
)
end

and I want to write a query like this:

Message.databaser(Message, current_user).all

But I could not write. Any help would be appreciated.

+3
source share
1 answer

I have an answer regarding the use of different databases based on each model. Perhaps this will point you in the right direction.

0
source

All Articles