Christopher Thomas
Christopher Thomas

Reputation: 13

"undefined method `title' for nil:NilClass" error in Ruby on Rails

I'm building a video website and I've been getting this error when I try to add a title to my static page where users can watch a video:

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>

And here's my movies_controller.rb file:

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

My watch method is above "private" in my controller file, which I'm told is one of the primary reasons why this error shows up. But every time I try to go to the page, the error still appears. Can someone tell me what I'm doing wrong?

Upvotes: 0

Views: 925

Answers (1)

user229044
user229044

Reputation: 239290

The error message is very clear: @movie is nil. Nowhere in your watch action do you try to define that variable as anything other than nil, and your before_action callback that populates @movie very clearly does not include watch in the list of actions for which it runs.

Upvotes: 1

Related Questions