2011-06-13 128 views
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 

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

回答

0

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

+0

数据库配置存储在数据库中。每个用户都有自己的数据库配置。当用户登录时,他的一些表必须使用用户自己的数据库。 – railslove 2011-06-14 10:38:54

+0

是的,只需使用'abstract_class = true'并连接到用户模型的db。你不必使用建立连接,你也可以使用你的用户模型的值。 – 2011-06-14 13:43:32