【发布时间】:2019-02-13 16:19:51
【问题描述】:
我正在尝试创建一个 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
我已尝试实现赞成/反对票功能 (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 作为支持的版本。
如果有人能对此有所了解,将不胜感激。
【问题讨论】:
-
我在控制器中看不到
upvote_from方法。你的意思是upvote_by? -
你说得对,应该是
upvote_by。我会编辑它。 -
您使用的是哪个版本的 gem?
-
0.11.1,最新版本。
标签: ruby-on-rails ruby nomethoderror acts-as-votable