在Rails6表单中显示关联的模型错误



我使用的是Rails 6.0.3.4和Ruby 2.7.2。以Rails入门教程为例,我想知道如何显示关联模型的表单验证错误。

显示页面

<p>
<strong>Title:</strong>
<%= @article.title %>
</p>

<p>
<strong>Text:</strong>
<%= @article.text %>
</p>

<h2>Comments</h2>
<%= render @article.comments %>

<h2>Add a comment:</h2>
<%= render 'comments/form' %>

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>

评论表格(这是有问题的表格(

<%= form_with(model: [ @article, @article.comments.build ], local: true) do |form| %>
<p>
<%= form.label :commenter %><br>
<%= form.text_field :commenter %>
</p>
<p>
<%= form.label :body %><br>
<%= form.text_area :body %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>

型号

class Comment < ApplicationRecord
belongs_to :article
validates :commenter, presence: true
end
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end

对于单个模型文章表单,错误可能显示如下。

<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

如何在评论表单中显示错误?当我在没有评论人的情况下提交评论时,它不会保存,所以验证正在进行,但我不知道如何显示这种类型表单的错误。

<% if @???????.errors.any? %> ###### What do I say here to get the comment errors?
<div id="error_explanation">
<h2>
<%= pluralize(@?????.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @?????.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>

1。为错误创建可重复使用的分部

# app/views/shared/_errors.html.erb
<div class="error_explanation">
<h2><%= pluralize(object.errors.count, "error") %> prohibited
this <%= object.model_name.singular %> from being saved:</h2>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>

还有一个小辅助方法:

# app/helpers/application_helper.rb
module ApplicationHelper
# Displays the errors for a model instance if there are any
def display_errors_for(object)
return unless object.errors.any?
render partial: 'shared/errors', 
locals: { object: object }
end
end

2.从表单生成器中获取对象

您总是可以通过#object方法访问表单生成器实例包装的模型,而不是使用实例变量:

<%= form_with(model: [ @article, @comment ], local: true) do |form| %>
# ...
<%= display_errors_for(form.object) %>
<% end %>

就像魔术一样,你可以用一行代码将错误添加到任何表单中。

不要使用@article.comments.build。这将始终将表单绑定到注释的新实例,而不是显示错误!它还将删除用户在表单中输入的任何内容…在控制器中分配变量。我不知道这是怎么悄悄进入指南的。

class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
@comment = @article.comments.new
end
end

最新更新