【问题标题】:Problems with Warden::Manager after_authentication callbacksWarden::Manager after_authentication 回调的问题
【发布时间】:2012-01-13 03:12:16
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:
    Warden::Manager.after_authentication do |user, auth, opts|
      Cart.create!(:user_id => user.id)
    end
    

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

    【讨论】:

      【解决方案2】:

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

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

      在应用程序控制器中:

      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。

      【讨论】:

      • 在 session[:cart_id] 为 nil 的情况下,您不必执行 Cart.find,因为您已经有了购物车。少一个数据库请求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多