我已經使用 Rails 有一段時間了,但我想我會嘗試一門課程來鞏固我的知識。
但是我已經對基本的保存/錯誤操作感到困惑。
我試圖在模型驗證失敗后顯示錯誤訊息。
如果模型驗證失敗,我render 'new'再次,模型實體應該有錯誤訊息的地方。但是,如果我嘗試列印錯誤訊息,就像<%= modelinstance.errors.inspect %>它只顯示一個空陣列一樣。
奇怪的是,如果我反而render :new, status: :unprocessable_entity很樂意渲染整個錯誤。
我只是想知道為什么會這樣,當 ruby?? on rails 指南允許字串版本時。
控制器:
...
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 %>'
...
uj5u.com熱心網友回復:
這是由于在 Rails 7 中引入了 Turbo。沒有這種狀態,Turbo 將不知道如何處理重定向。
您可以在這里閱讀更多相關資訊: https ://turbo.hotwired.dev/handbook/drive#redirecting-after-a-form-submission
否則,您可以禁用 Turbo,它應該恢復“正常”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431901.html
