Implementing vote_fu in a rails application (or alternatives)

I tried to implement a robust voting system in Rails for some time, but struggled. Initially, I built my own voting system, but was simplified.

In a nutshell, he simply increased the column votes_countin the model Answerusing a cache counter. This worked fine for me for a while, until I opened vote_fu and realized how much more reliable my voting system could be. I installed it right away and spent the whole weekend breaking my application, trying to get it to work.

I found here a few other stack overflow questions related to this plugin, but none of them came up with a final solution. Here is my code:

answers_controller.rb:

def vote_up
    answer = Answer.find(params[:id])
    current_user.vote_up(answer), :voter_id => current_user.id
    redirect_to :back
end

votes_controller.rb:

def create
  @quote = Answer.find(params[:answer_id])

  respond_to do |format|
    if current_user.vote(@answer, params[:vote])
      format.rjs  { render :action => "create", :vote => @vote }
      format.html { redirect_to root_url }
    else
      format.rjs  { render :action => "error" }
      format.html { render :action => "new" }
      format.xml  { render :xml => @vote.errors, :status => :unprocessable_entity }
    end
  end
end

answer.html.erb: ( , )

<span id="vote_form"  style="float: right;">
  <%= link_to "Vote up", :url => vote_up_answer_path(answer) %>
  /
  <%= link_to_remote "Down", :
    url => user_answer_votes_path(answer.user, answer,  :vote => :false, :format => :rjs), :method => :post
  %> 
</span>

<span id="<%= answer.id %>_vote_score" class="vote_score">
  <%= answer.votes_for - answer.votes_against %>
</span> 

routes.rb:

map.resources :users, :member => { :suspend => :put, :unsuspend => :put, :purge => :delete } do |user|
  user.resources :votes
  user.resources :answers do |answer|
    answer.resources :votes
  end
end
map.resources :answers, :has_many => :votes, :member => {:vote_up => :post, :vote_down => :post}

Rails 2.3.5.

- ? ? , ?

+3
2

, . , . User :

#In User.rb
acts_as_voter

#In Answer
acts_as_votable

, , rake:migrate db, :

u = User.first 
a = Answer.last 
u.votes_for(a)

, , :

def vote
  @question = Question.find(params[:id])
  if params[:vote] == 'up'      
    current_user.vote_for(@question)
  elsif params[:vote] == 'down'      
    current_user.vote_against(@question)
  end
  redirect_to @question
end
+1

jt . vote_for . , .

def vote
    @question = Question.find(params[:id])
    if params[:vote] == 'up'      
      current_user.vote_for(@question)
    elsif params[:vote] == 'down'      
      current_user.vote_against(@question)
    end
    redirect_to @question
  end
0

Source: https://habr.com/ru/post/1733815/


All Articles