2013-05-09 37 views
1

我目前正在嘗試使用thumbs_up實現喜歡和unlikes rails應用程序。我按照此頁上的說明操作:Clarification on how to use "thumbs_up" voting gem with Rails 3未定義的方法`voted_on?'爲零:使用thumbs_up的NilClass錯誤消息

用戶可以喜歡和不同的書。我有兩個按鈕,喜歡和不同,我想隱藏用戶的一個或另一個,取決於用戶目前的狀態。所以我想,如果一個人會是適當的這樣的:

<% if @user.voted_on?(@book) %>  
    <div class="unlike_button"><%= link_to("Unlike", unvote_book_path(book), method: :post) %></div> 
<% else %> 
    <div class="like_button"><%= link_to("Like", vote_up_book_path(book), method: :post) %></div> 
<% end %> 

,在我route.rb文件:

resources :books do 
    member do 
    post :vote_up 
    post :unvote 
    end 
end 

但是當我運行此我得到的錯誤信息:

未定義的方法`voted_on?'對於零:NilClass

有什麼我可能會做錯嗎?

更新

由於米沙的建議,我把它改爲current_user.voted_on。現在,我得到這個錯誤信息:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

下面是我的書控制器的片段

include UsersHelper 
include SessionsHelper 


    before_filter :signed_in_user, only: [:index] 
    before_filter :admin_user, only: :destroy 

    def index 
    array = Book.search(params[:search]) 
    @books = Kaminari.paginate_array(array).page(params[:page]).per(5) 

    end 

    def show 
    @book = Book.find(params[:id]) 
    #respond_to do |format| 
    #format.js 
    #end 
    end 


    def destroy 
    Book.find(params[:id]).destroy 
    flash[:success] = "Book deleted." 
    redirect_to books_url 
    end 

    def vote_up 
    begin 
     current_user.vote_for(@book = Book.find(params[:id])) 
     flash[:success] = "Liked!." 
     redirect_to books_url 
    end 
    end 

    def unvote 
    begin 
     current_user.unvote_for(@book = Book.find(params[:id])) 
     flash[:success] = "Unliked!." 
     redirect_to books_url 
    end 
    end 
+0

'@ user'是'nil'。你不是指'current_user.voted_on(@book)'?如果你想使用'@ user',你必須在某個地方定義它,而你顯然沒有這樣做。 – Mischa 2013-05-09 03:40:59

+0

你可以發佈你的控制器動作的其餘部分嗎? – pungoyal 2013-05-09 06:29:20

+0

正如Mischa說的,@user在這裏是零,你必須在控制器或助手中定義它,或者在偶數視圖中定義它。但是在控制器中定義這樣的變量更有意義。或者只是使用current_user如果你正在使用設計。 – Jyothu 2013-05-09 08:35:50

回答

-1

您應該更改您的聯繫方式從和 更改路線.rb

resources :books 

您還可以通過使用此代碼更新使用鏈路上的數據:

<%= link_to "Like", book, :method => :put %> 
or 
<%= link_to "Unlike", book, :method => :put %> 

和這正好與你的控制器 假設你在發表你的模型有is_liked布爾場

def update 
@post = Post.find(params[:id]) 

    if @post.is_liked? 
     @post.attributes = { 
     :is_liked => "f" 
    } 
    redirect_to posts_path, :flash => "Unliked" 
    else 
    @post.attributes = { 
     :is_liked => "t" 
     } 
    redirect_to posts_path, :flash => "Liked" 
    end 

end 
+0

請有一個看看錯誤信息。這個答案並不能解決他所得到的錯誤。 – Mischa 2013-05-09 03:55:34

+0

是的,但我在我的回答告訴在他的代碼的鏈接方法應該不是後應該是方法。 – 2013-05-09 06:05:16

+0

那麼答案是無關緊要的。 – pungoyal 2013-05-09 06:19:53

相關問題