针对SaaS HW2,出现了“undefined method 'keys' for nil:NilClass”的错误。

3

我正在尝试在Rails上运行一款面向SaaS课程的应用程序,在完成第二项作业时,每当我刷新页面都会出现以下错误:

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个小时。


1
“@ratings” 被定义在哪里?我没有看到它,所以 “@ratings.keys” 会给你一个错误。 - Philip Hallstrom
1个回答

14

让我们一起看看那个错误信息...

undefined method `keys' for nil:NilClass

这里有三个重要的部分:

  1. undefined method - 这是告诉你核心问题。问题在于你试图调用的方法不存在于你要调用它的对象中。
  2. keys - 这是告诉你你试图调用的方法。
  3. 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即可。

1
非常感谢!:D 我已经弄清楚了除了@ratings部分之外的所有内容。现在我明白了,它可以工作了!:D 非常感谢。 - har00n86

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接