使用acts_as_votable进行评论时如何定义upvote / downvote?

时间:2014-10-15 17:44:16

标签: ruby-on-rails ruby ruby-on-rails-4

我的评论资源嵌套在我的帖子资源中,两个资源都是act_as_votable。

我如何定义upvote / downvote?这是我现在正在做的事情(评论控制器):

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

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

这是新的并创建动作和参数:

def new
    @post = Post.find(params[:post_id])
    @comment = Comment.new(params[:id])
 end


def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.post_id = @post.id 
if @comment.save
  redirect_to @post
else

  redirect_to new_post_comment_path(post)
end
end

private

   def comment_params
      params.require(:comment).permit(:body, :post_id)

结束

这是我收到的错误消息:

 No route matches {:action=>"upvote", :controller=>"comment", :format=>nil, :id=>nil, 
 :post_id=>#<Comment id: 22, body: "test", user_id: 1, post_id: 4, created_at:         

 "2014-10-14 07:28:22", updated_at: "2014-10-14 07:28:22", cached_votes_total: 0,       

 cached_votes_score: 0, cached_votes_up: 0, cached_votes_down: 0,   

 cached_weighted_score: 0, cached_weighted_total: 0, cached_weighted_average: 0.0>} 
 missing required keys: [:id]

我的嵌套路线:

  resources :posts do
member do
  put "like", to: "posts#upvote"
  put "dislike", to: "posts#downvote"
end
resources :comments do
member do
  get 'upvote' => 'comment#upvote', as: :upvote
  get 'downvote' => 'comment#downvote', as: :downvote
end
end
end

评论/ index.html.erb:

<div class="comments">
<% @comments.each do |comment| %>
<p><%= comment.body %></p>


<div>
  <%= link_to "up", upvote_post_comment_path(comment) %>
  <%= link_to "down", downvote_post_comment_path(comment) %>
  <%= comment.score %>
</div>
<% end %>
</div>

1 个答案:

答案 0 :(得分:0)

我认为这里的关键是“无路由匹配”错误结束时的提示:

missing required keys: [:id]

我猜你的Comment对象有一个nil id。也许它还没有坚持下去?

此外,可能不相关,你有一个模棱两可的路线:

resources :comments do
  member do
    get 'upvote' => 'comment#upvote', as: :upvote
    get 'upvote' => 'comment#downvote', as: :downvote
  end
end

了解/comments/:id/upvote如何路由到两个不同的行为?