本文介绍了关于如何使用“thumbs_up"的说明;使用 Rails 3 投票的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Rails 3 应用程序上实现 thumbs_up 投票 gem,但说明不清楚关于实际执行.在需要 gem [gem 'thumbs_up'] 和创建并运行适当的迁移后 [rails 生成 thumbs_up &&rake db:migrate] README 解释如下:

I am attempting to implement the thumbs_up voting gem on a Rails 3 app, however the instructions are unclear on the actual implementation. After requiring the gem [gem 'thumbs_up'] and after creating and running the appropriate migration [rails generate thumbs_up && rake db:migrate] the README explains the following:

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

voter.vote_exclusively_for(voteable) #删除任何以前的投票特定选民,并投票支持.
voter.vote_exclusively_against(voteable) #删除任何以前的投票特定选民,并投反对票.*

我一直假设 README 示例中voter"和voteable"的使用是应用程序中对象的替代品,但对我来说用法仍然模糊不清.

I've been assuming that the use of 'voter' and 'voteable' in the README example are stand-ins for objects in the app, but the usage is still nebulous to me.

我的视图、控制器和 routes.rb 文件应该是什么样子的文字示例将是一个巨大的帮助.我花了几天时间试图弄清楚这一点!

A literal example of what my view, controller, and routes.rb file should look like would be a TREMENDOUS help. I've spent days trying to figure this out!

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

In my app, I have Users that vote on Posts - of which there are two types - Events and Links. Posts are called using <%= render :partial => @posts %> and each individual post uses as its view "_event.html.erb" or "_link.html.erb" - depending whether it is an event or a link.

推荐答案

希望我能帮到你.

生成器应该已经为您创建了一个投票模型.这是持有所有选票的模型,但您可以通过上述方法间接与之交互.

The generators should have created a Vote model for you. This is the model that holds all the votes, but that you interact with indirectly through the methods you've described above.

所以,对你来说:

class User < ActiveRecord::Base
  acts_as_voter
end

class Post < ActiveRecord::Base
  acts_as_voteable
end

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

That will get you set up with the thumbs_up methods in each of the models.

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

Then for example, if you have a controller action in PostsController that is linked to from an "up arrow" on your website, you can create a vote for that user for that post.

这样的视图:

<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>

和一个这样的 routes.rb:

and a routes.rb like this:

resources :posts do
  member do
    post :vote_up
  end
end

最后,在控制器中:

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

这篇关于关于如何使用“thumbs_up"的说明;使用 Rails 3 投票的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 20:02