Warden :: Manager after_authentication回调问题

时间:2012-01-13 03:12:17

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

如果Ruby是我的第一语言,这对我来说可能更简单,但无论如何,这是我的问题:

使用Rails 3.1,我试图通过Devise访问一些Warden Manager回调来创建一个新的' Cart'每次用户登录时。我将此逻辑放在我的ApplicationController中。问题是,当我创建一个购物车时,我想给它一个用户ID。我一直在尝试使用Devise的辅助方法current_user,但这不起作用。

最重要的是,我想知道为什么我无法从Warden :: Manager块中访问ApplicationController中定义的辅助方法或方法。但我也想知道如何编辑我的代码,以便我可以在块中使用Devise的current_user方法(以及我的current_cart方法,如下所示),而不会出现如下所列的错误。 < / p>

这是我的代码:

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

2 个答案:

答案 0 :(得分:5)

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

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

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