动态数据库连接

时间:2011-06-13 22:45:14

标签: ruby-on-rails ruby-on-rails-3

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

某些模型使用依赖于当前用户的其他数据库。现在我想稍微清除这段代码。我想写一个像这样的方法:

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

我想编写一个类似的查询:

Message.databaser(Message, current_user).all

但我不能写。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我有一个答案,涉及在每个模型的基础上使用不同的数据库。也许this会指出你正确的方向。