我正在尝试在Rails上运行一个应用程序,用于saas课程,作业2.每当我刷新页面时,我都会收到以下错误:
NoMethodError in MoviesController#index
undefined method `keys' for nil:NilClass
Rails.root: C:/Sites/RailsProjects/hw2_rottenpotatoes
Application Trace | Framework Trace | Full Trace
app/controllers/movies_controller.rb:24:in `block in index'
app/controllers/movies_controller.rb:23:in `each'
app/controllers/movies_controller.rb:23:in `index'
我的movies_controller.rb
文件:
class MoviesController < ApplicationController
def show
id = params[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
end
def index
redirect = false
if params[:sort]
@sorting = params[:sort]
elsif session[:sort]
@sorting = session[:sort]
redirect = true
end
if redirect
redirect_to movies_path(:sort => @sorting, :ratings => @ratings)
end
Movie.find(:all, :order => @sorting ? @sorting : :id).each do |mv|
if @ratings.keys.include? mv[:rating]
(@movies ||= [ ]) << mv
end
end
session[:sort] = @sorting
session[:ratings] = @ratings
end
def new
# default: render 'new' template
end
def create
@movie = Movie.create!(params[:movie])
flash[:notice] = "#{@movie.title} was successfully created."
redirect_to movies_path
end
def edit
@movie = Movie.find params[:id]
end
def update
@movie = Movie.find params[:id]
@movie.update_attributes!(params[:movie])
flash[:notice] = "#{@movie.title} was successfully updated."
redirect_to movie_path(@movie)
end
def destroy
@movie = Movie.find(params[:id])
@movie.destroy
flash[:notice] = "Movie '#{@movie.title}' deleted."
redirect_to movies_path
end
end
我对Rails非常陌生,并且仅仅花了4个小时就尝试了不同的东西。
答案 0 :(得分:12)
让我们来看看那个错误信息......
undefined method `keys' for nil:NilClass
这有三个重要部分:
undefined method
- 这告诉你核心问题。问题是,您尝试调用它的方法不存在您尝试调用它的方法。keys
- 这告诉您正在尝试呼叫的方法。nil:NilClass
- 这告诉你你在调用方法的内容。在您的情况下,这些信息不是直接有用 - 它并没有告诉您究竟要查找什么。然而, 告诉您,无论您要查找的是什么,都有nil
的值。 Rails.root: C:/Sites/RailsProjects/hw2_rottenpotatoes
这告诉你项目的根源,以防万一你完全忘记了你甚至在做什么。没关系。我们都有那些日子。
Application Trace | Framework Trace | Full Trace
app/controllers/movies_controller.rb:24:in `block in index'
app/controllers/movies_controller.rb:23:in `each'
app/controllers/movies_controller.rb:23:in `index'
这告诉你完全在哪里寻找你正在发生的错误。它就在第二行:app/controllers/movies_controller.rb:24
...文件movies_controller.rb
,行24
。
这可能是指这一行:
if @ratings.keys.include? mv[:rating]
您正在检查mv[:rating]
中是否有@ratings.keys
...但是您收到的错误告诉您,您正在keys
检查nil
}。这意味着@ratings
尚未设置。
因此,看起来您只需要在@ratings
操作的顶部附近设置index
。