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



我有一个回调,每个方法都能很好地工作。

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}

但是这个回调总是调用类别。id和我得到的错误是:在这个操作中多次调用Render和/或redirect

您无法在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

相关内容

最新更新