[英]“undefined method `title' for nil:NilClass” error in Ruby on Rails
我正在建立一個視頻網站,並且在嘗試向我的靜態頁面添加標題以供用戶觀看視頻時遇到此錯誤:
watch.html.erb
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-4">
<p>You're watching:</p>
<h1><%= @movie.title %></h1>
</div>
</div>
</div>
這是我的movies_controller.rb文件:
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def watch
end
def index
@movies = Movie.all
end
def show
@reviews = Review.where(movie_id: @movie.id).order("created_at DESC")
end
def new
@movie = current_user.movies.build
end
def edit
end
def create
@movie = current_user.movies.build(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
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
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 set_movie
@movie = Movie.find(params[:id])
end
private
def movie_params
params.require(:movie).permit(:title, :description, :movie_length, :director, :rating, :image)
end
end
我的watch方法位於控制器文件中的“ private”上方,這是出現此錯誤的主要原因之一。 但是每次我嘗試轉到該頁面時,仍然會出現錯誤。 有人可以告訴我我在做什么錯嗎?
錯誤消息非常清楚: @movie
為nil
。 在watch
動作中,您沒有嘗試將變量定義為nil
以外的任何變量,並且非常清楚地填充@movie
before_action
回調未在其運行的動作列表中包括watch
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.