AbstractController :: CommentsController中的DoubleRenderError #create

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

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: "alert('Recaptcha error!')".html_safe, layout: 'application' ) redirect_to article_path(@article) end end 

我收到此错误:

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

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

另请注意, redirectrender都不会终止执行操作,因此如果要在重定向后退出操作,则需要执行redirect_to(...) and return

不要将renderredirect_to结合使用。 您已经将application.html.erb文件渲染为布局,而html是您指定的script

如果你想使用render你必须知道这个没有在目标动作中运行任何代码,所以,如果你想“重新分配” @article变量,你将不得不使用redirect_to ,如果你想添加一些消息以通知用户然后您可以添加一条flash消息,然后您可以在视图中显示该消息:

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

然后在你看来:

 <% if flash[:error] %> 
<%= flash[:error] %>
<% end %>