2010-02-22 166 views
3

我一直在努力實現的Rails強大的表決系統有一段時間了,但一直在努力實現vote_fu。最初,我建立了自己的投票系統,但過於簡單。在Rails應用程序(或替代)

簡單地說,它只是使用計數器緩存遞增votes_count列在Answer模型。在我發現vote_fu並且意識到我的投票系統可以有多強大之前,這對我來說工作得很好。我立即安裝了它,並花了整個週末將我的應用程序拆分開來,試圖使其運行。

我發現對堆棧溢出一些其他的問題在這裏與此相關的插件,但沒有人真正有最終的解決方案上來。這裏是我的代碼:

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。

有沒有人有任何建議?我應該回到我的舊手工投票系統嗎?我還沒有聽說過另一個投票插件或方法嗎?

+0

Vote_fu是巨大的。什麼特別是不工作? – Jonathan 2010-02-22 00:16:54

+0

這對我來說也很棒!這就是爲什麼我真的想讓它工作! 看來,我的link_to接口不工作......它只是當我點擊時不添加任何投票。 此外,當我嘗試 U = User.first A = Answer.last u.votes_for(一) 我得到一個錯誤,如控制檯: 「未知屬性:選民」 ......我不知道如何糾正這一點。 – goddamnyouryan 2010-02-22 01:21:16

回答

1

我認爲第一步將得到它通過控制檯的工作。從您評論中的最後一個錯誤中,似乎您的模型設置不正確。在你User模型,你應該具備以下條件:

#In User.rb 
acts_as_voter 

#In Answer 
acts_as_votable 

此外,還要確保您已經應用rake:migrate到你的數據庫,然後在控制檯中試一下:

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 
0

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