2011-02-05 102 views
11

我試圖在Rails 3應用程序上實現thumbs_up投票寶石,但指令在實際實現上還不清楚。需要寶石後[寶石「thumbs_up」]和創建和運行適當的遷移後[軌產生thumbs_up & &耙分貝:遷移]自述說明如下:澄清如何使用「thumbs_up」投票寶石與Rails 3

要投上一票一個模型,你可以做到以下幾點:
*語法速記
voter.vote_for(voteable)#添加一個+1 投票
voter.vote_against(voteable)# 添加一個-1票
voter.vote(voteable, 表決)#添加無論是+1或-1投票: 表決=>真(+1),表決=>假(-1)

voter.vote_exclusively_for(voteable)# 由 移除所有以前的票特定選民,並投票。
voter.vote_exclusively_against(voteable)# 移除由 特定選民以往任何選票,票反對。*

我一直在假設自述使用「選民」和「voteable」的示例是應用程序中對象的替身,但對我來說,這種用法仍然是模糊的。

我的視圖,控制器和routes.rb文件應該看起來像一個字面示例將是一個TREMENDOUS幫助。我花了好幾天的時間來解決這個問題!

在我的應用程序,我有用戶對職位,投 - 其中有兩種類型 - 活動鏈接。帖子使用<%=渲染調用:局部=> @posts%>和每個單獨的交用作其視圖「_event.html.erb」或「_link.html.erb」 - 這取決於它是否是一個事件或一個鏈接。

回答

24

希望我能幫助你一點。

發電機應該爲您創建了一個Vote模型。這是保存所有選票的模型,但是您可以通過上述方法間接進行交互。

所以,爲您提供:

class User < ActiveRecord::Base 
    acts_as_voter 
end 

class Post < ActiveRecord::Base 
    acts_as_voteable 
end 

,將讓你設置與每個模型的thumbs_up方法。

然後,例如,如果您在PostsController中的控制器操作通過網站上的「向上箭頭」進行鏈接,則可以爲該用戶創建該帖子的投票。

像這樣的視圖:

<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %> 

和一個路由。RB是這樣的:

resources :posts do 
    member do 
    post :vote_up 
    end 
end 

最後,在控制器:

class PostsController < ApplicationController 
    def vote_up 
    begin 
     current_user.vote_for(@post = Post.find(params[:id])) 
     render :nothing => true, :status => 200 
    rescue ActiveRecord::RecordInvalid 
     render :nothing => true, :status => 404 
    end 
    end 
end 
+1

嘿brady8,能有一個以上的模型`acts_as_voter`?例如,假設我有一個`User`模型和一個`client`模型。他們都可以充當選民,它可以正常工作嗎? – marcamillion 2011-02-19 08:36:07

+4

是的,當然。 – bouchard 2011-02-28 07:53:13

0

這僅僅是一個布雷迪的回答延續。

布雷迪有下面的代碼在他看來

<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %> 

他的意思是..因爲的link_to默認使用:method => 'get' &他想使用後&得不到更新的記錄,所以他是用:method => 'post'

U可以使用<%= button_to( '投票這個職位!',vote_up_post_path(@post)%>,因爲默認情況下按鈕使用:method => :post

這樣的路徑應該是

resources :posts do 
    member do 
    post :vote_up 
    end 
end 

在這裏post :vote_up成員內部,其method => :post &不交控制器

,但如果你有決心使用link_to沒有:method => :post像這樣

<%= link_to('vote for this post!', vote_up_post_path(@post)) %> 

那麼你的路由應該是

resources :posts do 
    member do 
     get :vote_up 
    end 
end 

希望這有助於!

1

路由錯誤

沒有路由匹配{:行動=> 「vote_up」:控制器=> 「微柱」, :ID =>零}

這是鏈接我我正在使用並假設這是路由未被正確指定的地方。我跑耙路線,有一條路線叫vote_up_micropost。還有什麼我應該看看。謝謝

這裏是鏈接我加

<%= link_to('vote for this post!', 
    vote_up_micropost_path(@microposts), 
    :method => :post) %> 
相關問題