在Rails中显示嵌套资源的错误消息

我正在创建我的第一个应用程序,简单的博客,我不知道如何显示未通过validation的嵌套资源(注释)的错误消息。

这是为评论创建动作:

def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(comment_params) redirect_to post_path(@post) 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 

和:

   

prohibited this comment from being saved:

但我不知道什么是错的。

您无法从控制器渲染部分。 更好的选择就是创建一个new视图。

 class CommentsController def create if @comment.save redirect_to post_path(@post), success: 'comment created' else render :new end end end 

应用程序/视图/评论/ new.html.erb:

 <% if @comment.errors.any? %> 

<%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:

    <% @comment.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %> <%= render partial: 'form', comment: @comment %>

应用程序/视图/评论/ _form.html.erb:

 <%= form_for([@post, local_assigns[:comment] || @post.comments.build]) do |f| %> 

<%= f.label :commenter %>
<%= f.text_field :commenter %>

<%= f.label :text %>
<%= f.text_area :text %>

<%= f.submit %>

<% end %>