acts_as_votable,undefined方法`upvote_by'代表nil:NilClass

时间:2015-02-24 17:09:02

标签: ruby-on-rails ruby ruby-on-rails-4 vote

我正在尝试使用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

我得到这个错误“未定义的方法`upvote_by'为nil:NilClass”

谢谢

1 个答案:

答案 0 :(得分:2)

您的问题与acts_as_votable无关 - 您的实例变量尚未分配,因此实际上任何方法都会导致此错误。您必须取消评论评论行并进行更改:

before_action :upvote

before_action :upvote, except: :index

然而,这个逻辑似乎很可疑 - 为什么你会想要一个明星在用户编辑时被投票?简而言之:请澄清您的要求。