2011-07-21 67 views
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 

這允許多票投反對票。我如何設計它,以便用戶只能對每條評論進行一次投票,但是如果他們投了票或投票,他們就會保持跟蹤,所以他們有能力在他們想要的時候改變他們的投票。

+0

還請注意,在SO – KevinDTimm

+0

上搜索「每用戶一票」時發現許多結果您需要另一個模型來跟蹤投票。您可以使用唯一性約束來僅允許每個用戶投一票,這正是Mikhailov的答案。 –

+0

我正在閱讀這個答案,但是我怎麼做才能允許用戶稍後改變他的投票呢?可以說從-1到1 – Kevin

回答

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或任何其他寶石。

+0

感謝您使用這個方法,我從@mikhailov獲得了一些其他修改,並且我最終完成了它的工作 – Kevin

1

你或許可以添加到模型驗證,以確保數在數值上等於或小於1

validates :count, :numericality => { :less_than_or_equal_to => 1 } 
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 
+0

是的,我認爲我需要另一種投票模式,但我如何實現一種方式讓用戶稍後改變投票? – Kevin

+0

**更新**操作將通過回答和用戶id-s查找投票,然後更新其投票 – Anatoly

+0

您需要稍微提醒一下:爲您的投票選擇遷移和模型文件。屬性:[id],user_id:整數,comment_id:整數,is_up:布爾值;那麼您可以在您的投票模型中有一個範圍(或類函數)來返回給定評論的上/下投票數。更重要的是:您可以跟蹤哪個用戶投票選擇哪個評論 - 並讓用戶更改他們的投票! – emrass

相關問題