访问模型中的ApplicationControler变量

时间:2017-03-03 03:52:34

标签: ruby-on-rails ruby ruby-on-rails-4

我在ApplicationController中声明了一个全局变量,但是我尝试从任何模型访问它,但是当这样做时,变量在模型中是空的,就像在AplicationController中我指定的值

这是我的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

2 个答案:

答案 0 :(得分: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服务器)

答案 1 :(得分: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)

我想这是最简单的方法。