未定义的方法`voted_on?' for nil:使用thumbs_up的NilClass错误消息

时间:2013-05-09 03:33:55

标签: ruby-on-rails ruby-on-rails-3

我目前正在尝试使用thumbs_up实现喜欢和不喜欢rails app。我按照此页面上的说明操作:Clarification on how to use "thumbs_up" voting gem with Rails 3

用户可以喜欢和不同的书籍。我有两个按钮,喜欢和不同,我想隐藏用户中的一个或另一个,具体取决于用户当前状态。所以我想了一个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

有什么我可能做错了吗?

更新

正如Mischa建议的那样,我将其更改为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

1 个答案:

答案 0 :(得分:-1)

您应该将链接方法从发布更改为 put 和 将 routes.rb 更改为

resources :books

您还可以使用以下代码使用链接更新数据:

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

,这与您的控制器一致 假设您在Post模型中有一个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