I'm currently trying to implement likes and unlikes rails app using thumbs_up. I followed the instructions on this page: Clarification on how to use "thumbs_up" voting gem with Rails 3
Users can like and unlike books. I have 2 buttons, like and unlike and I would like to hide one or the other from the user, depending on the users current like status. So I figured an if else would be appropriate like this:
<% 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 %>
and in my route.rb file:
resources :books do
member do
post :vote_up
post :unvote
end
end
But when I run this I get the error message:
undefined method `voted_on?' for nil:NilClass
Is there anything I might be doing wrong?
Update
As Mischa suggested, I changed it to current_user.voted_on. Now I get this error message:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Below is a snippet of my Books controller
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