2016-07-22 65 views
0

我有一個錯誤顯示/編輯表單,其中包含用於添加註釋和附件的部分。呈現部分表單頁面上的驗證錯誤消息

當用戶試圖提交無效的附件類型或空的評論時,驗證會爲附件[using paperclip gem]發出錯誤[validates :comment, presence: true]和類似錯誤,現在發生這種情況時,我希望錯誤消息顯示在相同的錯誤形成。

回購是在@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

您可以通過向表單添加ajax來實現此目的。 '遠程:真的' – mrvncaragay

+0

@ Marv-C - 你可以告訴我們該如何實現? – HSD

回答

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 
+0

謝謝,'閃光[:錯誤]'事情工作正常。關於'@ comment.errorys.any'我已經給了一個嘗試,但是在做這個@comment變成零並且不會顯示錯誤消息,不知道爲什麼?我的理解是重定向以前的錯誤不會持續重定向,並且是一個新的請求。 – HSD

+0

您是否在模型中指定驗證? – Alex

+0

是的在模型中指定了驗證 – HSD