“Like”, “Dislike” plugin for rails

后端 未结 5 1040
不思量自难忘°
不思量自难忘° 2020-12-14 03:27

Is there any \"like\" , \"dislike\" plugin for rails...

I went through rating plugins... but all of them were 5 star rating plugins...

5条回答
  •  再見小時候
    2020-12-14 04:06

    I recommend creating the like and dislike option by taking on the classic vote model functionality.

    So you have Vote as a join table between the User and the Votable Item .

    A Vote value can work as Vote.value + 1 = Like, Vote.value -1 = Dislike, Vote.value = Neutral/Didn't vote.

    Your controller for your votable item can look like this :

    def like
      get_vote
      @vote.value += 1 unless @vote.value == 1
      @vote.save
      respond_to do |format|
        format.html
        format.js 
      end
    end
    
    def dislike
      get_vote
      @vote.value -= 1 unless @vote.value == -1
      @vote.save
      respond_to do |format|
        format.html
        format.js 
      end
    end
    
    private
    
    def get_vote
      current_item = @item.detect{|r| r.id == params[:id].to_i}
      @vote = current_item.votes.find_by_user_id(current_user.id)
      unless @vote
        @vote = Vote.create(:user_id => current_user.id, :value => 0)
        current_item.votes << @vote
      end
    end
    

    And for everyone's info, this question didn't deserve to be voted down. Its completely valid.

提交回复
热议问题