我安装了acts_as_votable gem,它在控制台中工作就像它应该的那样(就像在文档中说的那样)。 所以我的问题是如何为upvote和downvote按钮设置一个表单?或者它们只是链接?
这里是文档:github.com/ryanto/acts_as_votable/blob/master/README.markdown
我有一个用户和一个图片模型;用户应该能够喜欢这张照片。 图片视图中的代码,按钮应为:
<% for picture in @pictures %>
<p>
<%= image_tag picture.image_url(:thumb).to_s %>
</p>
<%= picture.created_at.strftime("%a, %d %b. %Y") %>, by
<%= link_to picture.user.name, picture.user %>
<h2> <%= link_to picture.name, picture %></h2>
[buttons here]
<%= picture.votes.size %> <% end %>
答案 0 :(得分:9)
执行此操作的一种方法是为up-downvotes添加自己的控制器操作。
我假设您的控制器中有current_user
方法。
# pictures_controller.rb
def upvote
@picture = Picture.find(params[:id])
@picture.liked_by current_user
redirect_to @picture
end
def downvote
@picture = Picture.find(params[:id])
@picture.downvote_from current_user
redirect_to @picture
end
# config/routes.rb
resources :pictures do
member do
put "like", to: "pictures#upvote"
put "dislike", to: "pictures#downvote"
end
end
# some view
<%= link_to "Upvote", like_picture_path(@picture), method: :put %>
<%= link_to "Downvote", dislike_picture_path(@picture), method: :put %>
答案 1 :(得分:5)
以下是我最终使用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
前置过滤器允许更多功能,因此我可以将其添加到任何可评论对象。我的节日恰好是节日,但你可以拍照或其他任何东西。查看acts_as_commentable文档和多态railscast以获取更多相关信息。这是我的第一篇文章,所以如果这是一个糟糕的代码,请告诉我。