在application_controller中设置类和方法变量

时间:2012-03-22 14:28:40

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

我在尝试从设计中获取current_user时遇到了实际问题,请从此处确定帐户ID,然后将此变量作为变量传递给此gem中的set_current_tenant_to方法:https://github.com/ErwinM/acts_as_tenant

在我的应用程序控制器中,我有:

class ApplicationController < ActionController::Base

  protect_from_forgery # See ActionController::RequestForgeryProtection for details      
  helper :all # include all helpers, all the time

  def get_current_account_id
    current_account_user = current_user
    current_account_id = current_account_user.account_id
    current_account_id
  end

  current_account = Account.find(get_current_account_id)
  set_current_tenant_to(current_account)

我知道get_current_account_id推断出正确的account_id,因为当我将它放在before_filter调用中时,我可以在日志中看到它输出正确的数字。但是,当我运行此操作时,我收到以下错误:

Routing Error

undefined local variable or method `get_current_account_id' for ApplicationController:Class

我将非常感谢任何有关如何使其发挥作用的建议或指示。

3 个答案:

答案 0 :(得分:0)

我猜它是在调用类级方法,而不是实例方法,所以你需要在self上调用它。另外,你真的不需要所有这些额外的变量:

class ApplicationController < ActionController::Base
  def self.get_current_account_id
    current_user.account_id
  end
end

答案 1 :(得分:0)

我想您要做的是创建一个过滤器来设置当前租户。你应该这样做:

class ApplicationController < ActionController::Base
  before_filter :set_tenant_to_current_account
  def set_tenant_to_current_account
    current_account = Account.find(current_user.account_id)
    set_current_tenant_to(current_account)
  end

  def set_current_tenant_to(account)
    # Your business logic here.
    @current_tenant = account
  end
end

编辑:放置一些存根方法代码来表示set_tenant_to

答案 2 :(得分:0)

在应用程序控制器中定义任何自定义方法时,必须使用此

调用它

呼叫。

 class ApplicationController < ActionController::Base

   before_filter :get_current_account_id


    protect_from_forgery # See ActionController::RequestForgeryProtection     
   helper :all # include all helpers, all the time

   def get_current_account_id
    current_account_user = current_user
    current_account_id = current_account_user.account_id
    set_tentant_id(current_account_id)
   end

   def set_tentant_id
    #your logic
   end
 end

我希望它能干得很好.....