在部分表单的页面上呈现验证错误消息

Render validation error messages on the page for partial forms

我有一个错误 show/edit 表单,其中包含用于添加评论和附件的部分内容。

当用户尝试提交无效的附件类型或空评论时,验证会抛出错误 [validates :comment, presence: true] 和类似的附件 [using paperclip gem],现在发生这种情况时,我想要错误消息显示在同一个错误表单上。

仓库位于@GitHub Link

在我的表演形式中我有

show.html.erb
<%= render partial: 'bug_attachments/bug_form' %>
<%= render partial: 'comments/form' %>

comments/form.html.erb
<% @comment = Comment.new %>
<%= form_for [@bug, @comment] do |f| %>
<%= f.text_area :body, placeholder: "Add a comment" %>
<%= f.submit 'Add Comment'%>
<% end %>


comments_controller.rb
class Bugs::CommentsController < ApplicationController
before_action :authenticate_user!
before_action :set_bug

def create
  @comment = @bug.comments.new comment_params
  @comment.user = current_user
  if @comment.save
    redirect_to bug_path(@comment.bug_id), notice: 'Comment added successfully'
  else
    # Here I am setting @bug = 1 since when the user posts the comments, the @bug becomes nil.
    @bug = Bug.find(1)
    render 'bugs/show'
    # redirect_to @comment, alert: 'Unable to save your comment'
  end
 end
 private
  def set_bug
   @bug = Bug.find(params[:bug_id])
  end
  def comment_params
   params.require(:comment).permit(:body)
 end
end

请问有什么帮助吗?

你可以这样做(为你的项目编辑):

<% if @comment && @comment.errors.any? %>
  <ul>
  <% @comment.errors.full_messages.each do |error_message| %>
    <li><%= error_message %></li>
  <% end %>
  </ul>
<% end %>

另一种有趣的方式是瞬间完成:

在您的控制器上:

if @comment.errors.any?
  flash[:error] = @comment.full_messages.join(', ')
  redirect_to #somewhere
else