2

我安装了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 %>
4

2 回答 2

9

一种方法是为赞成和反对票添加您自己的控制器操作。我假设您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 %>
于 2013-02-22T15:36:55.500 回答
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

before 过滤器允许更多功能,因此我可以将其添加到任何可注释的对象中。我碰巧是节日,但你可以做照片或任何事情。查看acts_as_commentable 文档和多态railscast 以获得更多信息。这是我的第一篇文章,所以如果这是糟糕的代码,请告诉我。

于 2013-02-27T00:19:36.373 回答