acts_as_votable,nil:NilClass 的未定义方法“upvote_by”

acts_as_votable , undefined method `upvote_by' for nil:NilClass

我正在尝试让用户 acts_as_votable gem 让用户投票给星星

这是我的星控

class StarsController < ApplicationController
    before_filter :authenticate_user!, except: [:index, :show]
    before_action :upvote 
    def index
        @stars = Star.all.order("created_at DESC")
    end

  def upvote 
   # @star = Star.find(params[:id])
   @star.upvote_by current_user
   redirect_to @star
  end

    def show
        @star= Star.find(params[:id])
    end

    def new
    end

    def create
        @star =Star.new(stars_params)
        @star.save

        redirect_to @star
    end




    private 
    def stars_params
        params.require(:star).permit(:name , :description , :image)
    end

end

这是我的明星模特

 class Star < ActiveRecord::Base


has_many :books

has_attached_file :image, :styles => { :small => "150x150>" }
validates_attachment_presence :image
validates_attachment_size :image, :less_than => 5.megabytes
validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png']
acts_as_votable
end

和溃败

Rails.application.routes.draw do
  resources :books

  devise_for :users, path_names: {sign_in: "login", sign_out: "logout"}

  resources :stars do 
    member do 
      put "like" , to: "stars#upvote"

    end
  end


  root 'stars#index'
end

我收到这个错误 "undefined method `upvote_by' for nil:NilClass"

感谢

您的问题与 acts_as_votable 没有真正的关系 - 您的实例变量尚未分配,因此实际上任何方法都会导致此错误。您必须取消注释注释行并更改:

before_action :upvote

before_action :upvote, except: :index

然而,这种逻辑似乎有问题 - 为什么您希望用户在编辑时点赞星标?简而言之:请明确您的要求。