我正在使用devise
并尝试下一个:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :is_worker
def is_worker
if user_signed_in?
@email = current_user.email
if @email && Worker.find_by_email(@email).nil?
redirect_to '/tasksadmins'
else
redirect_to '/workers'
end
else
redirect_to '/users/sign_in'
end
end
end
当我尝试进入网站时:localhost:3000/tasksadmins
,我得到了:
Oops! It was not possible to show this website
The website at http://localhost:3000/tasksadmins seems to be unavailable. The precise error was:
Too many redirects
It could be temporarily switched off or moved to a new address. Don't forget to check that your internet connection is working correctly.
我该如何解决?
答案 0 :(得分:7)
before_filter
适用于每个请求。这就是为什么它一次又一次地重定向。
您可能只希望过滤特定操作:
before_filter :is_worker, only: :index
另一个解决方案是检查#is_worker
中是否需要重定向:
redirect_to '/workers' unless request.fullpath == '/workers'
修改强>
另一种方法是跳过重定向目标操作的前置过滤器。例如:
class WorkersController < ApplicationController
skip_before_filter :is_worker, only: :index
# …
end
答案 1 :(得分:0)
就我而言:
users_controller.rb
before_action :logged_in?, only: :new
def new
@user = User.new
render layout: "session"
end
和
application_controller.rb
def logged_in?
redirect_to users_new_url unless current_user.present?
end
当我尝试重定向到“用户/新”页面时,发生了相同的错误。 这仅仅是因为我试图重定向到'users / new'页面,并且“ def logging_in?” 也正在重定向到同一页面。
然后,我更改了 application_controller.rb 代码,如下所示:
def logged_in?
redirect_to root_url unless current_user.blank?
end
错误已解决。