澄清如何在Rails 3中使用"thumbs_up"投票宝石

neo*_*eon 11 vote-up-buttons ruby-on-rails-3

我试图在Rails 3应用程序上实现thumbs_up投票gem,但是指令在实际实现上并不清楚.在需要gem [ gem'sontumb_up' ]并且在创建并运行适当的迁移[ rails generate thumbs_up && rake db:migrate ]之后,README解释了以下内容:

要为模型投票,您可以执行以下操作:
*速记语法
voter.vote_for(可投票)#添加+1投票
voter.vote_against(可投票)#添加-1投票
voter.vote(可投票,投票)#Adds +1或-1投票:投票=>真(+1),投票=>假(-1)

voter.vote_exclusively_for(可投票)#删除该特定投票人的任何先前投票,并投票赞成.
voter.vote_exclusively_against(可投票)#删除该特定选民以前的任何投票,并投反对票.*

我一直认为在README示例中使用'voter'和'voteable'是应用程序中对象的替身,但是对我来说使用仍然模糊不清.

我的视图,控制器和routes.rb文件应该是什么样子的文字示例将是一个非常有用的帮助.我花了好几天试图解决这个问题!

在我的应用程序中,我有用户在帖子上投票 - 其中有两种类型 - 事件链接.使用<%= render:partial => @posts%>调用帖子,并且每个帖子使用其视图" _event.html.erb "或" _link.html.erb " - 取决于它是事件还是链接.

bou*_*ard 24

希望我可以帮助你一点.

生成器应该为您创建一个投票模型.这是包含所有投票的模型,但您通过上述方法间接进行交互.

所以,对你来说:

class User < ActiveRecord::Base
  acts_as_voter
end

class Post < ActiveRecord::Base
  acts_as_voteable
end
Run Code Online (Sandbox Code Playgroud)

这将使您在每个模型中使用thumbs_up方法进行设置.

然后,例如,如果您在PostsController中有一个控制器操作,该控制器操作链接到您网站上的"向上箭头",则可以为该帖子创建该用户的投票.

这样的观点:

<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>
Run Code Online (Sandbox Code Playgroud)

和一个routes.rb像这样:

resources :posts do
  member do
    post :vote_up
  end
end
Run Code Online (Sandbox Code Playgroud)

最后,在控制器中:

class PostsController < ApplicationController
  def vote_up
    begin
      current_user.vote_for(@post = Post.find(params[:id]))
      render :nothing => true, :status => 200
    rescue ActiveRecord::RecordInvalid
      render :nothing => true, :status => 404
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 是的,当然了. (4认同)