Ruby on rails AbstractController::CommentsController#create中的DoubleRenderError
我有一个小问题,此代码有效:Ruby on rails AbstractController::CommentsController#create中的DoubleRenderError,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个小问题,此代码有效: 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
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
def创建
@article=article.find(参数[:article\u id])
如果验证(u recaptcha),
@comment=@article.comments.create(comment_参数)
重定向到文章路径(@article)
其他的
渲染(
html:“警报('Recaptcha error!')”。html\u safe,
布局:“应用程序”
)
重定向到文章路径(@article)
结束
结束
我得到这个错误:
AbstractController::CommentsController#create中的DoubleRenderError
在此操作中多次调用渲染和/或重定向
请注意,您只能调用render或redirect,每个操作最多只能调用一次
还要注意的是,无论是
redirect
还是render
都不会终止操作的执行,因此如果您想在重定向后退出操作,您需要执行类似于redirect\u to(…)的操作,并返回不要将render
与redirect\u to
结合使用。您已经将application.html.erb
文件呈现为布局,html是您指定的脚本
如果你想使用渲染
,你必须知道这个操作不会在目标操作中运行任何代码,因此,如果你想“重新分配”@article
变量,你必须使用重定向到
,如果你想添加一些消息来通知用户,那么你可以添加一条flash
消息,然后可以在视图中显示:
...
else
flash[:error] = 'Recaptcha error!'
redirect_to @article
end
<% if flash[:error] %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
那么在你看来,
...
else
flash[:error] = 'Recaptcha error!'
redirect_to @article
end
<% if flash[:error] %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
我建议您尝试将_渲染为_字符串而不是渲染
资料来源:
关于它工作正常,谢谢!我用error
来举例说明。您可以根据需要添加闪存键。但是如果--我得到这个错误:文章中的NameError#显示未定义的局部变量或#为什么?谢谢,已经决定了。