2014-01-19 172 views
3

我試圖實施投票系統的帖子中的評論使用行爲作爲可投資的寶石。在這個階段,我得到這個錯誤評論與投票行爲投票

ActionController::UrlGenerationError in Posts#show 

其次 -

No route matches {:action=>"upvote", :controller=>"comments", :id=>nil, :post_id=>#<Comment id: 5, post_id: 3, body: "abc", created_at: "2014-01-12 20:18:00", updated_at: "2014-01-12 20:18:00", user_id: 1>, :format=>nil} missing required keys: [:id]. 

我和路線相當薄弱。

我的routes.rb

resources :posts do 
    resources :comments do 
    member do 
     put "like", to: "comments#upvote" 
     put "dislike", to: "comments#downvote" 
    end 
    end 
end 

評論控制器

def upvote 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.find(params[:id]) 
    @comment.liked_by current_user 
    redirect_to @post 
end 

def downvote 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.find(params[:id]) 
    @comment.downvote_from current_user 
    redirect_to @post 
end 

_comment.html.erb

<%= link_to "Upvote", like_post_comment_path(comment), method: :put %> 
<%= link_to "Downvote", dislike_post_comment_path(comment), method: :put %> 

回答

1

你也應該通過後idlike_post_comment_pathlike_post_comment_path(post, comment)

+0

謝謝。但我想它應該是like_post_comment_path(@post,comment)。接受它是正確的,因爲它導致瞭解決方案。 – Shuvro

1

這款寶石的美妙之處在於您可以輕鬆地將投票附加到任何對象。那麼爲什麼不建立一個票控制器,可以在你的應用程序的任何位置處理任何對象的投票? 這裏是我的解決方案

的routes.rb

resources :votes, only: [] do 
    get 'up', on: :collection 
    get 'down', on: :collection 
    end 

votes_controller.rb

class VotesController < ApplicationController 
    before_action :authenticate_user! 
    before_action :identify_object 

    def up 
    @object.liked_by current_user 
    redirect_to :back # redirect to @object if you want 
    end 

    def down 
    @object.downvote_from current_user 
    redirect_to :back # redirect to @object if you want 
    end 

    private 

    def identify_object 
    type = params[:object] 
    @object = type.constantize.find(params[:id]) 
    end 
end 

然後在您的視圖中的投票鏈接

up_votes_path(object:'Post', id:post.id) 
down_votes_path(object:'Post', id:post.id)