5

我目前有一个评论控制器,它有方法 vote_up 和 vote_down 这就是我的 vote_up 当前的工作方式。

我的评论模型有描述和计数字段。

  def vote_up
    @comment = Comment.find(params[:comment_id])
    @comment.count += 1
    if @comment.save
      flash[:notice] = "Thank you for voting"
      respond_to do |format|
        format.html { redirect_to show_question_path(@comment.question) }
        format.js
      end
    else
      flash[:notice] = "Error Voting Please Try Again"
      redirect_to show_question_path(@comment.question)
    end
  end

这允许上下多次投票。我将如何设计它,以便用户每条评论只能投票一次,但以某种方式跟踪他们是否投了赞成票或反对票,因此他们也可以根据需要更改投票。

4

3 回答 3

3

你可以做这样的事情。它禁止相同的投票,但允许将投票更改为相反的投票(这是一个竖起大拇指/竖起大拇指的系统)。

def vote(value, user) # this goes to your model

  #find vote for this instance by the given user OR create a new one
  vote = votes.where(:user_id => user).first || votes.build(:user_id => user)

  if value == :for
    vote_value = 1
  elsif value == :against
    vote_value = -1
  end

  if vote.value != vote_value
    vote.value = vote_value
    vote.save
  end
end

移民:

def self.up
    create_table :votes do |t|
    t.references :comment, :null => false
    t.references :user, :null => false
    t.integer :value, :null => false
  end
  add_index :votes, :post_id
  add_index :votes, :user_id
  add_index :votes, [:post_id, :user_id], :unique => true
end

或者,您可以使用名为thumbs_up或任何其他的 gem。

于 2011-07-21T15:20:40.713 回答
2
class AnswersController < ApplicationsController
  def vote
    #params[:answer_id][:vote]
    #it can be "1" or "-1"
    @answer = Answer.find(params[:answer_id])
    @answer.vote!(params[:answer_id][:vote])
  end

  def show
    @answer = Answer.find(params[:answer_id])
    @answer.votes.total_sum
  end

end

class Answer < ActiveRecord::Base
  has_many :votes do
    def total_sum
      votes.sum(:vote)
    end
  end


  def vote!(t)
    self.votes.create(:vote => t.to_i)
  end

end

class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user

  validates_uniqueness_of :user_id, :scope => :answer_id
end
于 2011-07-21T13:37:59.577 回答
1

您也许可以在模型中添加验证以确保 count 在数值上等于或小于 1

validates :count, :numericality => { :less_than_or_equal_to => 1 }
于 2011-07-21T13:37:27.147 回答