在rails 4.2中使用before_filter时重定向循环

时间:2015-07-21 11:36:42

标签: ruby-on-rails ruby ruby-on-rails-4 admin

大家好,所以我想做的很简单。

我想要一个前置过滤器来检查当前用户是否为admin,即使管理员访问索引页面也会自动将他重定向到管理面板(例如localhost:3000,这是普通用户的根URL)

对于admin用户,路径为localhost:3000 / admin /

到目前为止,我已编写了这些代码块,但会导致重定向循环

在我的application_controller.rb中我有这个

include SessionsHelper
before_filter :admin_users?


  private
    def admin_users?
      if current_user.admin?
        redirect_to admin_path
      end
    end

并且sessions_perb中的current_user方法如下

  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

这里是用户控制器

class UsersController < ApplicationController

  before_filter :admin_users? # application controller method

  before_action :logged_in_user, only: [:index,:edit,:update] # is in Application Controller
  before_action :correct_user, only: [:edit,:update]
  before_action :admin_user, only: :destroy


  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      @user.send_activation_email
      flash[:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      render 'new'
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end


  private

    def user_params
      params.require(:user).permit(:name,:email,:password,:password_confirmation)
    end

    # before filters


    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end

end

任何线索?

1 个答案:

答案 0 :(得分:1)

接下来是问题。您已将重定向放在application_controller.rb内,所有其他控制器都继承,甚至是Admin控制器。

你必须做下一步:

从您的before_filter :admin_user中移除ApplicationController,并将其仅放在您要检查用户是否为管理员的位置,以及除管理员控制器之外的所有控制器。

您有重定向循环,因为当您来到admin_path时,管理员控制器将重定向到admin_path。