2011-06-13 96 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