我正在尝试创建一个 Reddit 克隆,其中用户以及 upvote 和 downvote 帖子。我已经为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 %>
...
但是当我尝试对帖子进行投票时,我得到
PostsController 中的 NoMethodError#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 , acts_as_votable的 GitHub 页面仅列出了5.0和5.1作为受支持的版本。
如果有人能对此有所了解,将不胜感激。