【发布时间】:2016-10-06 22:37:06
【问题描述】:
我正在创建我的第一个应用程序,即简单的博客,但我不知道如何显示未通过验证的嵌套资源 (cmets) 的错误消息。
这是 cmets 的创建操作:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to post_path(@post)
end
这是评论表单:
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :text %><br />
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
我试过了:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
if @comment.save
redirect_to post_path(@post)
else
render '/comments/_form'
end
end
和:
<% if @comment.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@comment.errors.count, "error") %> prohibited
this comment from being saved:
</h2>
<ul>
<% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
但我不知道怎么了。
【问题讨论】:
-
嗨,欢迎来到 Stack Overflow。您能否扩展“我不知道出了什么问题”。 - 解释你观察到的和你期望看到的?
-
hmmm 实际上我认为您的问题是这一行:
render '/comments/_form'- 您应该改为重新渲染“新”操作,例如render :action => :new... 而不仅仅是单独渲染表单,但整个新页面。
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5