Ruby 在应用程序控制器中设置类和方法变量
我在尝试从Desive获取当前用户时遇到了真正的问题,从这里确定帐户id,然后将其作为变量从这个gem传递给set_current_tenant_to方法: 在我的应用程序控制器中,我有:Ruby 在应用程序控制器中设置类和方法变量,ruby,ruby-on-rails-3,devise,Ruby,Ruby On Rails 3,Devise,我在尝试从Desive获取当前用户时遇到了真正的问题,从这里确定帐户id,然后将其作为变量从这个gem传递给set_current_tenant_to方法: 在我的应用程序控制器中,我有: class ApplicationController < ActionController::Base protect_from_forgery # See ActionController::RequestForgeryProtection for details helper
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)
如果您能给我一些建议或建议,我将不胜感激。我猜它是在调用类级方法,而不是实例方法,所以您需要自己调用它。此外,您真的不需要所有这些额外的变量:
class ApplicationController < ActionController::Base
def self.get_current_account_id
current_user.account_id
end
end
class ApplicationController
我想你要做的是创建一个过滤器来设置当前租户。您应该这样做:
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
class ApplicationController
编辑:放置一些存根的方法代码来表示
将租户设置为当您在应用程序控制器中定义任何自定义方法时,必须使用此
打电话
class ApplicationController
我希望它能很干净很好地工作……谢谢你的尝试,但它不起作用。在我的控制器中使用此选项:def self.get\u current\u account\u id current\u user.account\u id end current\u account=account.find(get\u current\u account\u id)将当前租户设置为(current\u account)
我现在得到以下响应:路由错误未定义的局部变量或ApplicationController:Class的方法“current\u user”
混淆源于类与实例方法的冲突。。。乍一看,租户文档看起来很有趣,因为它们似乎是在类设置中运行的,但这会将帐户锁定到第一次运行,而不是在每次请求时都运行它。。。我建议跟那个gem的作者澄清一下……是的,这就是我的想法,但当我运行这个时,我得到:NoMethodError in FooController#index undefined method
set_current_tenant_to'for#app/controllers/application_controller.rb:36:set_tenant_to#current_account'Ok,发生这种情况是因为您没有在控制器中的任何位置定义此方法。您在哪里定义“set_current_tenant_to”方法?这里将其设置为gem的一部分:在此方面的任何帮助都将不胜感激。
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
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