2017-03-03 101 views
0

我在ApplicationController中聲明瞭一個全局變量,但是我試圖從任何模型中訪問它,但是當這樣做的時候變量在模型中是空的,因爲我在AplicationController中分配了一個值在模型中訪問ApplicationControler變量

這是我的ApplicationController

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
    before_action :base 

    def base 
    @empresa2 = current_usuario.empresa_id 
    end 
end 

這是我的模型Logdatabase

class Logdatabase < ActiveRecord::Base 
    self.abstract_class = true 

    if @empresa2 == "28" 
    establish_connection(:development) 
    else 
    establish_connection(:otrabase) 
    end 

end 
+0

理想情況下,您不應該嘗試從模型中的控制器訪問變量。在MVC體系結構中,模型,視圖和控制器分別承擔責任,您應該堅持這一點。即使那樣,你想訪問,張貼你嘗試過的代碼,然後嘗試從社區獲得幫助 – Pramod

+0

@Pramod好吧,我加了帖子。在這種情況下,我如何將ActionController變量傳遞給模型? – LuisC

回答

1

在這種情況下,我不得不控制器設置連接:

class ApplicationController < ActionController::Base 
    before_action :set_database 

    def set_database 
    empresa2 = current_usuario.empresa_id 
    configuration_name = emprase2 == '28' ? :development : :otrabase 
    ActiveRecord::Base.eastablish_connection(configuration_name) 
    end 

end 

但是它看起來像你正試圖使您的生產服務器交換機動態的生產和開發數據庫之間。我不會推薦這個,而是設置一個單獨的服務器(或者如果你真的無法做到這一點,然後使用虛擬服務器名稱或替代端口號在同一服務器上設置第二個Web服務器)

0

如果你想通過將一個變量的內容添加到您的模型中,您可以在模型中定義一個接受參數的方法。

在你的模型Empresa與:

def receive_variable_from_countroller(variable) 
#do what you want with the variable 
end 

在您的控制器Empresa與:

#define your variable 
variable = "foo" 
Empresa.receive_variable_from_controller(variable) 

我想這將是做到這一點的最簡單方法。