Ruby 在 Rails - "undefined method `[]' for nil:NilClass" 使用 acts_as_votable gem

Ruby on Rails - "undefined method `[]' for nil:NilClass" when using acts_as_votable gem

我正在尝试创建一个 Reddit 克隆,用户可以在其中投赞成票和投反对票 posts。我已经安装 运行 acts_as_votable gem (https://github.com/ryanto/acts_as_votable):

的必要迁移
# app/models/user.rb
class User < ApplicationRecord
    has_many :posts
    devise :database_authenticatable, :registerable, :trackable, :validatable
    ...
    acts_as_voter
end

# app/models/post.rb
class Post < ActiveRecord::Base
    belongs_to :user
    ...
    acts_as_votable
end

我还应该提到我正在使用单个 table 继承来简化对每种类型 post:

的处理
# app/models/text_post.rb
class TextPost < Post
...
end

# app/models/link.rb
class Link < Post
...
end

我已尝试实现 upvote/downvote 功能 (http://www.mattmorgante.com/technology/votable):

# config/routes.rb
...
resources :posts do
    member do 
        put "like", to: "posts#upvote"
        put "dislike", to: "posts#downvote"
    end
    ...
end
...

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
    before_action :authenticate_user!, except: :index
    ...
    def upvote
        @post = Post.find(params[:id])
        @post.upvote_by current_user
        redirect_to :back
    end

    def downvote
        @post = Post.find(params[:id])
        @post.downvote_by current_user
        redirect_to :back
    end
end

# app/views/posts/index.html.erb
...
<% @posts.each do |post| %>
    ...
    <%= link_to like_post_path(post), method: :put do %>
        <i class="fa fa-arrow-up"></i>
    <% end %>
    ...
    <%= link_to dislike_post_path(post), method: :put do %>
        <i class="fa fa-arrow-down"></i>
    <% end %>
    ...
<% end %>
...

但是当我尝试对post投票时,我得到

PostsController 中没有方法错误#upvote

nil:NilClass

的未定义方法“[]”

在我的控制器中的这一行:

@post.upvote_by current_user

即使我在不​​使用 current_user 的情况下在控制台中手动尝试,我也会得到相同的错误:

irb(main):001:0> user = User.first
...
irb(main):002:0> post = Post.first
...
irb(main):003:0> post.upvote_by user
...
Traceback (most recent call last):
    1: from (irb):3
NoMethodError (undefined method `[]' for nil:NilClass)

我不确定我的代码是否有问题,或者这可能是兼容性问题,因为我正在使用 Rails 5.2.0 和 GitHub acts_as_votable 页面仅列出 5.05.1 作为受支持的版本。

如果有人能对此有所说明,将不胜感激。

upvote_by 似乎是 vote_up 的别名,也许您使用的不是教程中的相同 gem 版本?

https://github.com/ryanto/acts_as_votable/blob/599995f7ec5aa0f8a04312768fc956e9003d32d4/lib/acts_as_votable/votable.rb#L15

尝试改用 vote_up,因为它看起来像原始方法,它应该适用于未设置 upvote_by 别名的版本。

嗨,好久不见,但我认为您可能没有在控制器中设置 post。

NoMethodError in PostsController#upvote
undefined method `[]' for nil:NilClass

错误告诉您您正在尝试对尚未设置的 class 进行投票。你必须在控制器

中设置class
before_action :set_post, only: [:show, :edit, :update, :destroy, :upvote, :downvote]