Rails 5官方指南5.10节疑问:验证错误为何未被重置
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
createaction. You build an@articlewith the submitted params, then try to save it. - When validation fails,
@article.savereturnsfalse, and theelseblock runs:render 'new'. - Crucially:
renderdoes NOT trigger thenewaction in your controller. It doesn't run@article = Article.newat all. Instead, it just takes the current@articleinstance (the one that failed validation, complete with error messages and the user's submitted form data) and passes it directly to thenew.html.erbtemplate.
Why This Isn't a Bug—It's a Feature!
Rails does this intentionally to improve user experience:
- If it created a brand new
Articleinstance (like thenewaction does), you'd lose all the text the user already typed in the form. - By reusing the failed
@articleinstance, 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

