Rails 7 failed save 仅在我呈现状态时显示错误

Rails 7 failed save only shows errors if I render with a status

我已经在 rails 工作了一段时间,但我想我应该尝试一门课程来巩固我的知识。

但我已经对基本的 save/error 操作感到困惑。

我正在尝试在模型验证失败后显示错误消息。

如果模型验证失败,我会再次render 'new',模型实例应该有错误信息。但是,如果我尝试打印 <%= modelinstance.errors.inspect %> 之类的错误消息,它只会显示一个空数组。

奇怪的是,如果我改为 render :new, status: :unprocessable_entity 它很乐意呈现整个错误。

我只是想知道为什么会这样,当 rails 指南上的 ruby 允许字符串版本时。

控制器:

...
def index
    articles = Article.all

    render locals: {
        articles: articles
    }
end

def new
    @article = Article.new
end

def create
    @article = Article.new(article_params)

    if @article.save
        redirect_to @article
    else
        render :new, status: :unprocessable_entity
    end

end
...

查看:

<h1>Create a new article</h1>

<% if @article.errors.any? %>
    <h2>The following errors prevented the article from saving:</h2>
    <% @article.errors.full_messages.each do |msg| %>
        <%= msg %>
    <% end %>
<% end %>

    ...
    <%= form_with scope: @article, url: articles_path, local: true do |f| %>
        <p>
            <%= f.label :title %>
            <%= f.text_field :title %>
        </p>
        <p>
            <%= f.label :description %>
            <%= f.text_area :description %>
        </p>
        <p>
         <%= f.submit %>
        </p>
    <% end %>'
    ...

这是由于在 Rails 7 中引入了 Turbo。如果没有这个状态,Turbo 将不知道如何处理重定向。

您可以在此处阅读更多相关信息: https://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission

否则,您可以只禁用 Turbo,它应该会恢复到“正常”状态。