如果 Ruby 是我的第一语言,这对我来说可能会更简单,但无论如何,这是我的问题:
使用 Rails 3.1,我尝试使用 Devise 访问一些 Warden Manager 回调,以在每次用户登录时创建一个新的“购物车”。我将此逻辑放在我的 ApplicationController 中。问题是,当我创建一个购物车时,我想给它一个用户 ID。我一直在尝试使用 Devise 的辅助方法 current_user 但这不起作用。
最重要的是,我想知道为什么我不能从 Warden::Manager 块中访问我的辅助方法或 ApplicationController 中定义的方法。但我也想知道如何编辑我的代码,这样我就可以在块中使用 Devise 的 current_user 方法(以及我的 current_cart 方法,如下所示),而不会出现如下所示的错误。
这是我的代码:
class ApplicationController < ActionController::Base
helper :all
helper_method :current_user
protect_from_forgery
before_filter :fetch_categories
.
.
.
def current_cart
@current_cart ||= Cart.find_by_user_id(current_user.id)
end
Warden::Manager.after_authentication do |user, auth, opts|
Cart.create!(:user_id => current_user.id)
end
end
这是错误:
NameError in Devise::SessionsController#create
undefined local variable or method `current_user' for ApplicationController:Class