我正在尝试在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个小时,尝试了不同的东西。
发布于 2013-08-03 04:50:44
让我们来看看这条错误消息...
undefined method `keys' for nil:NilClass这其中有三个重要的部分:
undefined method -这是告诉你核心问题。问题是,您试图调用的方法对于您试图将其命名为on.keys的东西并不存在-这是告诉您正在尝试call.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中...但是您得到的错误告诉您,您正在nil上检查keys。这意味着还没有设置@ratings。
因此,看起来您只需要在index操作的顶部附近设置@ratings即可。
https://stackoverflow.com/questions/18025697
复制相似问题