如何设置只有用户已登录时才设计RegistrationsController来显示sign_up页面?

时间:2012-03-21 06:25:56

标签: ruby-on-rails ruby authentication devise

我试图通过谷歌找到解决方案,但是在SO中却找不到...
This是唯一的问题。它只有一个答案,它被接受,但对我不起作用......这是我的代码:

class RegistrationsController < Devise::RegistrationsController

  before_filter :authenticate_user!

  def new
    puts "Method new was called"
    super
  end

end

当我未在localhost:3000/sign_up页面登录时,正常显示并打印Method new was called。如果我还没有登录,我希望控制器将我重定向到sign_in页面。当然我可以用new方法检查并重定向,但这不是一个好的解决方案......我确信还有更多优雅的方式。我甚至尝试使用prepend_before_filter :authenticate_user!,但它也不起作用。

编辑

我在routs.rb

中为此控制器定义了路由
devise_for :users, :controllers => { :sessions => "sessions", :registrations => "registrations" }

2 个答案:

答案 0 :(得分:9)

Devise::RegistrationsController默认为require_no_authentication before filter

所以需要跳过它:

class RegistrationsController < Devise::RegistrationsController
  skip_before_filter :require_no_authentication
  before_filter :authenticate_user!

  def new
    puts "Method new was called"
    super
  end

end

答案 1 :(得分:3)

skip_before_filter :require_no_authentication

before_filter :authenticate_user!

不再有效。

改为使用authenticate_scope!