2015-03-02 15 views
0

在這個系統中,你可以發佈問題和對它們發表評論,它使用acts_as_votable gem,這樣用戶就可以upvote/downvote評論。我想顯示一個按鈕,用於給予好評/ downvote,而不是一個鏈接,所以我認爲這樣做:button_to助手無效評論在Rails 4中拋出'沒有路由匹配'

現在
<h2>Comments</h2> 
<% @question.comments.order('cached_votes_up DESC').each do |comment| %> 
    <% unless comment.errors.any? %> 
    <p><strong>Commenter:</strong> <%= comment.user.username %></p> 
    <p><strong>Comment:</strong><%= comment.body %></p> 

    <%= button_to_if !comment.new_record?, 'Upvote', { 
    :action => 'upvote', 
    :controller => 'comments', 
    :question => { 
     :question_id => @question.id 
    }, 
    :comment => comment.id 
    }, 
    :class => 'btn btn-default' %> 

    <%= button_to_if !comment.new_record?, 'Downvote', { 
    :action => 'downvote', 
    :controller => 'comments', 
    :question => { 
     :question_id => @question.id 
    }, 
    :comment => comment.id 
    }, 
    :class => 'btn btn-default' %> 
    <% end %> 
<% end %> 

<h2>Add a comment</h2> 

<% if @comment && @comment.errors.any? %> 
    <% @comment.errors.full_messages.each do |msg| %> 
    <li><%= msg %></li> 
    <% end %> 
<% end %> 
<%= form_for([@question, @question.comments.build]) do |f| %> 
    <p> 
    <%= f.label :body %><br> 
    <%= f.text_area :body %> 
    </p> 
    <p> 
    <%= f.submit %> 
    </p> 
<% end %> 

,發表評論時,有效一切都很正常。但是,當Rails的評論已經提交,但是無效拋出一個錯誤:

No route matches { 
    :action=> "upvote", 
    :comment=> 3, 
    :controller=> "comments", 
    :question=> { 
     :question_id=> 2 
    }, 
    :question_id=> "2-test-question" 
} 

這是因爲問題的意見不具有ID但因爲它是無效的,因此一直沒有保存到數據庫。然而,它仍然被納入在視圖中呈現的評論集合中。用<% unless comment.errors.any? %>包裝按鈕代碼似乎沒有做任何事情。

最初,我有button_to幫助程序來創建按鈕,但由於它不起作用,我試圖用button_to_if幫助程序包裝,以便它可以在呈現按鈕之前評估條件。不幸的是,我試過的所有東西都評估爲真。助手代碼:

module ApplicationHelper 
    # Render the button only if the condition evaluates to true 
    def button_to_if (condition, name = nil, options = nil, html_options = nil, &block) 
    if condition 
     button_to(name, options, html_options, &block) 
    end 
    end 
end 

從評論控制器相關的方法來創建註釋:

class CommentsController < ApplicationController 
    before_action :authenticate_user! 

    def create 
    @question = Question.find(params[:question_id]) 
    @comment = @question.comments.build(comment_params) 
    @comment.userid = current_user.id 
    if @comment.save 
     redirect_to @question 
    else 
     render 'questions/show' 
    end 
    end 

    private 
    def comment_params 
     params.require(:comment).permit(:author, :body) 
    end 
end 

註釋模型只是簡單的presencelength驗證。我知道這工作正常。這個問題似乎在button_to幫手,但在我的生活中,我無法弄清楚什麼是錯的。任何建議將不勝感激。

+0

您確定錯誤是由無效評論造成的嗎?錯誤消息中的'comment => 3'使得它看起來像註釋有id(3)? – basiam 2015-03-02 21:58:40

+0

是的,提交空白/太短評論時出現此錯誤;如果評論符合「長度」要求,則一切正常。 – Ben 2015-03-02 22:01:13

+0

那麼這個評論如何具有ID? :) – basiam 2015-03-02 22:41:55

回答

0

原來這是一個路由錯誤; :id未在button_to散列中定義,因此Rails無法正確地路由它。奇怪的是,它只是在評論發佈之後才顯示出來。

相關問題