[英]Rails: one view, model and it's associated model
So, for example, case from http://guides.rubyonrails.org/getting_started.html As you can see, if you try to create invalid post, you will see error messages: 因此,例如,以http://guides.rubyonrails.org/getting_started.html中的情况为例。如您所见,如果尝试创建无效的帖子,则会看到错误消息:
<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
How to implement error messages rendering for associated Comment model, keeping in mind that comment creation form is placed in posts/show view? 考虑到将注释创建表单放置在帖子/显示视图中,如何实现相关注释模型的错误消息呈现?
Form code is usually kept in the folder of the matching model in a _form.html.erb
partial that is rendered in both new.html.erb
and edit.html.erb
(to see a good example, generate a scaffold for a sample model). 表单代码通常以
_form.html.erb
部分的形式保存在匹配模型的文件夹中,该部分在new.html.erb
和edit.html.erb
中都呈现(要查看一个很好的示例,请为示例模型生成支架 )。
What you can do in your case is render this comments form partial in the posts show action. 在您的情况下,您可以做的是将此评论表单部分呈现在post show动作中。
app/views/posts/show.html.erb
<%= render 'comments/form', comment: @comment || @post.comments.build # Whatever you have here %>
app/views/comments/_form.html.erb
<%= form_for comment do |f| %>
<%= render 'error_messages', target: comment %>
...
<% end %>
In addition, showing error messages usually is the same in all forms, so in order to remove duplication, you can extract this code into a seperate partial. 此外,显示错误消息的所有形式通常都是相同的,因此,为了删除重复项,可以将此代码提取到单独的部分中。
app/views/application/error_messages.html.slim # here is slim syntax, convert as nescessary
/ error explanation
/
/ = render 'shared/error_explanation', target: @school
/
- if target.errors.any?
.error-messages
h4 Please correct the following fields:
ul
- target.errors.full_messages.each do |message|
li = message
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.