3

Acts as votable gem を使用して、投稿のコメントに投票システムを実装しようとしています。この段階で、このエラーが発生しています

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

私はルートにかなり弱いです。

私のルート.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 %>
4

2 に答える 2

1

idまた、いいねで投稿を渡す必要がありlike_post_comment_pathますlike_post_comment_path(post, comment)

于 2014-01-19T08:20:24.880 に答える
1

この gem の優れた点は、任意のオブジェクトに簡単に投票できることです。では、アプリのどこからでも、任意のオブジェクトの投票を処理できる投票コントローラーを構築してみませんか? ここに私の解決策があります:

ルート.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)
于 2016-03-27T18:01:26.160 に答える