我目前正在尝试使用 thumbs_up 实现喜欢和不喜欢的 Rails 应用程序。我按照此页面上的说明进行操作:Clarification on how to use "thumbs_up" vote gem with Rails 3
用户可以喜欢和不喜欢书籍。我有 2 个按钮,喜欢和不喜欢,我想对用户隐藏一个或另一个,这取决于用户当前的喜欢状态。所以我想一个 if else 会像这样合适:
<% 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
下面是我的 Books 控制器的片段
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