我正在尝试在 Rails 上运行一个应用程序,用于 saas 类(class),家庭作业 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 个小时尝试不同的东西。
最佳答案
让我们浏览一下该错误消息...
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
中...但是您得到的错误告诉您您在 nil
上重新检查 keys
。这意味着 @ratings
尚未设置。
因此,看起来您只需要将 @ratings
设置在该 index
操作顶部附近的某个位置即可。
关于ruby-on-rails - 未定义方法 `keys' 为 nil :NilClass for saas hw2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025697/