[英]acts_as_votable , undefined method `upvote_by' for nil:NilClass
[英]Ruby on Rails - "undefined method `[]' for nil:NilClass" when using acts_as_votable gem
我正在尝试创建一个 Reddit 克隆,用户可以在其中对帖子投赞成票和反对票。 我已经为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
我还应该提到我使用单表继承来简化对每种类型的帖子的处理:
# 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 %>
...
但是当我尝试对帖子进行投票时,我得到了
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,并且acts_as_votable的 GitHub 页面仅将5.0和5.1列为受支持的版本。
如果有人能对此有所了解,将不胜感激。
upvote_by
似乎是一个别名vote_up
,也许你不使用本教程相同的宝石版本?
尝试使用vote_up
代替,因为它看起来像原始方法,它应该适用于未设置upvote_by
别名的版本。
嗨 它已经很长时间了,但我认为您可能没有在控制器中设置您的帖子。
NoMethodError in PostsController#upvote
undefined method `[]' for nil:NilClass
该错误告诉您,您正在尝试对尚未设置的类进行投票。 你必须在控制器中设置类
before_action :set_post, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.