控制器未从Upvote链接接收comment.id

时间:2017-12-04 06:15:16

标签: ruby-on-rails acts-as-votable

我正在尝试将Upvote函数与acts_as_votable gem一起使用。我遇到的问题是,当我将鼠标悬停在Upvote链接上时,我可以看到comment.id没有给出URL预览,然后当我点击Upvote时,确定的错误消息告诉我:

Couldn't find Comment with 'id'=#
<Comment::ActiveRecord_Relation:0x007f813b169658> 

我的观点中的评论循环如下所示:

 <div class="box">
 <% @comment.each do |w| %>
    <tr>        
      <td><b><%= w.title %></b></td><br>
      <td><%= w.location %></td><br>
      <td><%= w.body %></td><br> 
      <%= link_to "upvote", like_comment_path(@comment), method: :put 
      %><br>
    </tr>
  <% end %>
 </div> 

我的 CommentsController

def upvote
  @comment = Comment.find(params[:id])
  @comment.upvote_by current_user
  redirect_to comments_path
end

我的配置/路由

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

这感觉它应该是非常简单的东西,但我无法弄清楚为什么没有给出id,所以非常感谢帮助: - )

1 个答案:

答案 0 :(得分:0)

我假设您的@comment是评论的集合。如果是这样,那么您应该将@comment变量重命名为@comments并在视图中迭代@comments集合,如下所示:

<div class="box">
 <% @comments.each do |comment| %>
    <tr>        
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br> 
      <%= link_to "upvote", like_comment_path(comment), method: :put 
      %><br>
    </tr>
  <% end %>
 </div> 

如您所见,您可以创建link_to更新您的评论项目,如下所示: <%= link_to "upvote", like_comment_path(comment), method: :put