我安装了acts_as_votable宝石,它工作在控制台像它应该(像它在文档中说的)。 所以我的问题是如何建立一个形式给予好评和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 %>
这样做的一个办法是增加你自己的控制器动作上调和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 %>
以下是我结束了与acts_as_commentable宝石做了。 因此,我认为这应该与你有任何意见的对象工作。
在我_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
该过滤器之前允许更多的灵活性,所以我可以将它添加到任何commentable对象。 矿正好是节日,但你可以做的图片或任何东西真的。 退房acts_as_commentable文档,并在该信息的多态性railscast。 这是我的第一篇文章,所以如果这是很可怕的代码,请告诉我。