【问题标题】:AbstractController::DoubleRenderError in CommentsController#createAbstractController::DoubleRenderError in CommentsController#create
【发布时间】:2017-07-09 00:57:46
【问题描述】:

我有一个小问题,这段代码有效:

def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    redirect_to article_path(@article)
  end
end

为什么这段代码不起作用?:

def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    render(
      html: "<script>alert('Recaptcha error!')</script>".html_safe,
      layout: 'application'
    )
    redirect_to article_path(@article)
  end
end

我收到此错误:

AbstractController::DoubleRenderError in CommentsController#create 在此操作中多次调用渲染和/或重定向。

请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。

还要注意redirectrender都不会终止动作的执行,所以如果你想在重定向后退出动作,你需要做类似redirect_to(...) and return的操作。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    不要将renderredirect_to 结合使用。您已经将 application.html.erb 文件呈现为布局,而 html 是您分配的 script

    如果您想使用render,您必须知道这个不会在目标操作中运行任何代码,因此,如果您想“重新分配”@article 变量,您必须使用@ 987654327@,如果你想添加一些消息来通知用户,那么你可以添加一个flash 消息,然后你可以在你的视图中显示:

    ...
    else
      flash[:error] = 'Recaptcha error!'
      redirect_to @article
    end
    

    那么在你看来:

    <% if flash[:error] %>
      <div class="error">
        <%= flash[:error] %>
      </div>
    <% end %>
    

    【讨论】:

    • 很好用,谢谢!
    • 我使用error 只是为了举例说明。您可以根据需要添加闪存键。
    • 但是如果 -
      - 我得到这个错误:NameError in Articles#show undefined local variable or method `error' for # :0x007fe7e5025448> 为什么?
    【解决方案2】:

    我建议你尝试 render_to_string 而不是 render

    来源:https://api.rubyonrails.org/v6.1.0/classes/AbstractController/Rendering.html

    问候

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 2014-07-02
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多