我正在研究一个项目,对于我的生活,我不确定发生了什么。我的代码工作得比较早,现在我正在
NoMethodError in MoviesController#upvote
当我尝试对某部电影投票时,这是我的“movie_controller.rb”
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!
# GET /movies
# GET /movies.json
def index
@movies = Movie.all
end
# GET /movies/1
# GET /movies/1.json
def show
end
# GET /movies/new
def new
@movie = Movie.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
@movie = Movie.new(movie_params)
respond_to do |format|
if @movie.save
format.html { redirect_to @movie, notice: 'Movie was successfully created.' }
format.json { render :show, status: :created, location: @movie }
else
format.html { render :new }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if @movie.update(movie_params)
format.html { redirect_to @movie, notice: 'Movie was successfully updated.' }
format.json { render :show, status: :ok, location: @movie }
else
format.html { render :edit }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
@movie.destroy
respond_to do |format|
format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' }
format.json { head :no_content }
end
end
def upvote
@movie.upvote_from current_user
redirect_to movies_path
end
def downvote
@movie.downvote_from current_user
redirect_to movies_path
end
private
def set_movie
@movies = Movie.find(params[:movie_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def movie_params
params.require(:movie).permit(:title, :image)
end
end
特别是它说是行有问题:
private
def set_movie
@movies = Movie.find(params[:id])
end
我还会附上好路线。谢谢你们。
Rails.application.routes.draw do
devise_for :users
root 'home#index'
resources :movies do
put "like", to: "movies#upvote"
put "unlike", to: "movies#downvote"
end
end
答案 0 :(得分:0)
问题是您要设置@movies
变量而不是@movie
。这就是你获得undefined method upvote_from' for nil:NilClass def upvote @movie.upvote_from
更改代码的这一部分
private
def set_movie
@movies = Movie.find(params[:id])
end
到这个
private
def set_movie
@movie = Movie.find(params[:id])
end