2

如果 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
4

2 回答 2

5
Warden::Manager.after_authentication do |user, auth, opts|
  Cart.create!(:user_id => user.id)
end

在 after_authentication 块中,您无权访问 current_user。相反,使用作为参数传递的新认证的用户对象。

于 2012-02-08T01:21:53.960 回答
0

好吧,我真的不喜欢回答我自己的问题,但是因为我觉得有义务不回答任何问题:

我最终做的基本上是完全回避整个回调的事情。尽管这可能与我的情况不同,但这就是我所做的:

在应用程序控制器中:

before_filter :authenticate_user!, :only => :current_cart

这样,用户必须登录才能调用 current_cart。并将 current_cart 更改为:

def current_cart
  session[:cart_id] ||= Cart.create(:user_id => current_user.id).id
  @current_cart ||= Cart.find(session[:cart_id])
end

所以 current_cart 实例化一个新的购物车,如果它还不存在的话。您还可以在其他可能影响您的购物车的控制器中执行 before_filter 操作,例如 LineItems 或 Products。

于 2012-01-13T04:29:44.687 回答