You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5官方指南5.10节疑问:验证错误为何未被重置

Why Does the Error Message Persist When Rendering the 'new' View?

Great question! This is a super common gotcha when you're getting started with Rails form validations—let's break down exactly what's going on here.

The Key Difference: render vs. redirect_to

The confusion comes from misunderstanding what render 'new' actually does in your create action. Here's the play-by-play:

  • When you submit your form, it hits the create action. You build an @article with the submitted params, then try to save it.
  • When validation fails, @article.save returns false, and the else block runs: render 'new'.
  • Crucially: render does NOT trigger the new action in your controller. It doesn't run @article = Article.new at all. Instead, it just takes the current @article instance (the one that failed validation, complete with error messages and the user's submitted form data) and passes it directly to the new.html.erb template.

Why This Isn't a Bug—It's a Feature!

Rails does this intentionally to improve user experience:

  • If it created a brand new Article instance (like the new action does), you'd lose all the text the user already typed in the form.
  • By reusing the failed @article instance, the template can display the user's previous input and the validation errors, so they don't have to start from scratch.

What Would Happen If You Used redirect_to Instead?

If you changed the else block to:

redirect_to new_article_path

Then you would lose the error messages. That's because redirect_to sends a whole new HTTP request to your server, which triggers the new action, creating a fresh, empty Article instance with no errors attached.

To Sum It Up

Your new action's @article = Article.new never runs when you render 'new' from create. The template is using the failed validation instance from the create action, which is why the error messages stick around. This is exactly how Rails is designed to work for form handling!

内容的提问来源于stack exchange,提问作者tac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:14:24