我有一个错误显示/编辑表单,其中包含添加注释和附件的部分内容。
当用户尝试提交无效的附件类型或空注释时,验证会抛出错误[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
请问这里有什么帮助吗?
答案 0 :(得分:0)
您可以这样做(为您的项目编辑):
<% 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