如何在 rails 控制器中使用 after_action 回调?

How to use after_action callback in rails controller?

我有一个回调,每个方法都可以正常工作。

class PostsController < ApplicationController # :nodoc:
  def index
    @category = Category.friendly.find(params[:category_id])
    check_user_pro! if @category.id  == 3
  end

  def show
    @post =Post.find(params[:id])
    @category = @post.category
    check_user_pro! if @category.id  == 3
  end

  private


  def check_user_pro!
     if @current_user.present? && (is_not_an_admin! || !@current_user.profile.professional?)
     redirect_to(root_path)
  end
end

我想使用如下回调: after_action :check_user_pro!, only: %i[index show] if -> {@category.id == 3}

但是这个回调总是调用 category.id 并且我得到这个错误:Render and/or redirect were called multiple times in this action

您不能在 after_action 中重定向或呈现,因为该操作已经呈现或重定向,您可以做的是做一个 before_action,它将在请求到达操作之前重定向请求。它看起来像这样:

class PostsController < ApplicationController # :nodoc:

  before_action :check_user_pro!, only: %i[index show], if: -> { category.id == 3 }

  def index
  end

  def show
    @post     = Post.find(params[:id])
    @category = @post.category
  end

  private

  def check_user_pro!
    redirect_to(root_path) if @current_user.present? && (is_not_an_admin! || !@current_user.profile.professional?)
  end

  def category
    @category ||= Category.friendly.find(params[:category_id])
  end

end