【问题标题】:How to use after_action callback in rails controller?如何在 Rails 控制器中使用 after_action 回调?
【发布时间】:2021-07-02 14:40:09
【问题描述】:

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

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 -&gt; {@category.id == 3}

但是这个回调总是调用 category.id 并且我得到这个错误:在这个动作中多次调用渲染和/或重定向

【问题讨论】:

  • @rubrique 在你的代码中定义在哪里?
  • 对不起...这是一个错误我已经更新了我的问题

标签: ruby-on-rails callback ruby-on-rails-6


【解决方案1】:

您不能在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多