Вопрос

I'm trying to implement a voting system to the comments in the posts using Acts as votable gem. At this stage I'm getting this error

ActionController::UrlGenerationError in Posts#show 

followed by -

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

I'm pretty weak with routes.

my routes.rb

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

comments controller

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 %>
Это было полезно?

Решение

You should also pass id of the post in like_post_comment_path like like_post_comment_path(post, comment)

Другие советы

The beauty of this gem is that you can attach votes easily to any object. So why not build a votes controller that can handle votes for any object, from anywhere in your app? Here's my solution:

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

Then the vote links in your view

up_votes_path(object:'Post', id:post.id)
down_votes_path(object:'Post', id:post.id)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top