多次调用 Render and/or 重定向

Render and/or redirect called multiple times in action

我正在使用 Devise 和 Pundit。 要创建新的个人资料页面,用户必须获得授权才能这样做。 自从我第一次实施以来,它一直运行良好,但今天它才开始出现错误消息:

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

这是我的应用程序控制器的代码:

    rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
    ...

    private

    def user_not_authorized(exception)
        flash[:alert] = "Sorry, you are not authorized to perform this action."
        redirect_to(request.referrer || root_path)
    end

这是我的 ProfilePage 控制器:

def new
  @profile_page = ProfilePage.new
  authorize @profile_page
end

def create
  @profile_page = ProfilePage.new(profile_page_params)
    respond_to do |format|
      if @profile_page.save
        format.html { redirect_to @profile_page, notice: 'Profile page was successfully created.' }
        format.json { render :show, status: :created, location: @profile_page }
      else
        format.html { render :new }
        format.json { render json: @profile_page.errors, status: :unprocessable_entity }
      end
    end
    authorize @profile_page
  end

有人建议我在下面添加这行代码 flash[:alert]:

self.response_body = nil

但现在我的用户再次被重定向到 'new profile' 页面,而不是成功的个人资料页面。它还告诉用户他们无权完成此操作,尽管它已授权他们这样做。

在创建操作中,您必须在保存记录之前放置授权逻辑:

你得搬家

authorize @profile_page

在创建操作的顶部,在初始化 @profile_page 之后,像这样:

def create
  @profile_page = ProfilePage.new(profile_page_params)
    authorize @profile_page

    respond_to do |format|
      if @profile_page.save
        format.html { redirect_to @profile_page, notice: 'Profile page was successfully created.' }
        format.json { render :show, status: :created, location: @profile_page }
      else
        format.html { render :new }
        format.json { render json: @profile_page.errors, status: :unprocessable_entity }
      end
    end
end