这也是我最终使用acts_as_commentable gem 的方式。所以我认为这应该适用于您有评论的任何对象。
在我的 _comment.html.erb 视图中
<%= link_to "Upvote", {:controller =>"comments", :action => "upvote", :id => comment.id}, :class => 'btn', method: :put %>
<%= link_to "Downvote", {:controller =>"comments", :action => "downvote", :id => comment.id}, :class => 'btn', method: :put %>
在我的 routes.rb 文件中
put '/comments/:id/:action' => 'comments#upvote'
put '/comments/:id/:action' => 'comments#downvote'
然后在我的评论控制器中
class CommentsController < ApplicationController
before_filter :load_commentable
before_filter :find_comment, :only => [:upvote, :downvote]
def upvote
current_user.upvotes @comment
redirect_to(@comment.commentable)
end
def downvote
@comment.downvote_from current_user
redirect_to(@comment.commentable)
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
@commentable = resource.singularize.classify.constantize.find(id)
end
def find_comment
@comment = Comment.find(@commentable.id)
end
end
before 过滤器允许更多功能,因此我可以将其添加到任何可注释的对象中。我碰巧是节日,但你可以做照片或任何事情。查看acts_as_commentable 文档和多态railscast 以获得更多信息。这是我的第一篇文章,所以如果这是糟糕的代码,请告诉我。