如何使用simple_form gem显示嵌套表单的错误消息

时间:2018-08-19 11:05:24

标签: ruby-on-rails simple-form

我创建了博客,并具有使用rails 5.1.2和simle_form 4.0.0创建评论的能力。 应用程序有两种形式-第一种用于创建博客文章,第二种用于创建评论。嵌套在帖子显示页面中的评论表单。两种表单的验证都可以正常工作,但是注释表单无法显示错误消息的问题。如何实现呢?

发布模型: app / models / post.rb

class Post < ApplicationRecord
  has_many :comments, dependent: :destroy
end

评论模型: app / models / comment.rb

class Comment < ApplicationRecord
  belongs_to :post
  validates :comment_content, presence: true, length: { maximum: 5000 }
end

评论控制器: app / controllers / comments_controller.rb

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:comment_content))
    redirect_to post_path(@post)
  end
end

评论表: app / views / comments / _form.html.erb

<%= simple_form_for([@post, @post.comments.build]) do |f| %>
  <%= f.input :comment_content, input_html: { class: 'texture' }, wrapper: false, label_html: { class: 'label'
  } %>

  <%= f.button :submit, 'Leave a reply', class: "btn btn-primary" %>
<% end %>

评论部分: app / views / comments / _comment.html.erb

<%= comment.comment_content %>

发布后页面,其中呈现评论形式: app / views / posts / show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <!-- Post details -->
</p>

<%= render @post.comments %>

<%= render 'comments/form' %>

路线:

Rails.application.routes.draw do
  resources :posts do
    resources :comments
  end
end

1 个答案:

答案 0 :(得分:0)

首先,您需要添加

<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

进入注释表单以呈现错误。

此外,您还需要在CommentsController中更改create动作-如果验证失败,它应该重新呈现表单。

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment].permit(:comment_content))
  if @comment.save
    redirect_to post_path(@post), notice: 'Comment was successfully created.'
  else
    render 'posts/show'
  end
end