ruby on rails - How to implement one vote per user per comment? -


i have comment controller has method vote_up , vote_down how vote_up works.

my comment model has description , count field.

  def vote_up     @comment = comment.find(params[:comment_id])     @comment.count += 1     if @comment.save       flash[:notice] = "thank voting"       respond_to |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 

this allows multiple vote , downs. how design user can vote once per comment somehow keep track if voted or down, have ability change vote if want too.

you this. prohibits identical votes allows changing vote opposite (it's thumbs up/thumbs down system).

def vote(value, user) # goes model    #find vote instance given user or create new 1   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 

migration:

def self.up     create_table :votes |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 

alternatively, use gem called thumbs_up or other.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -