评论投票与行为是可投票的

时间:2014-01-19 08:15:24

标签: ruby-on-rails voting-system

我正在尝试使用Acts作为可投票宝石,对帖子中的评论实施投票系统。在这个阶段,我收到了这个错误

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]. 

我的路线非常弱。

my 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 %>

2 个答案:

答案 0 :(得分:1)

您还应该在id like_post_comment_path中传递帖子的like_post_comment_path(post, comment)

答案 1 :(得分: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)