我目前正在嘗試使用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
'@ user'是'nil'。你不是指'current_user.voted_on(@book)'?如果你想使用'@ user',你必須在某個地方定義它,而你顯然沒有這樣做。 – Mischa 2013-05-09 03:40:59
你可以發佈你的控制器動作的其餘部分嗎? – pungoyal 2013-05-09 06:29:20
正如Mischa說的,@user在這裏是零,你必須在控制器或助手中定義它,或者在偶數視圖中定義它。但是在控制器中定義這樣的變量更有意義。或者只是使用current_user如果你正在使用設計。 – Jyothu 2013-05-09 08:35:50