Rails4:nil的未定义方法`failed_attempts':NilClass

时间:2015-06-23 10:01:39

标签: ruby-on-rails

构建一个刽子手游戏并在Games#show中获取NoMethodError,未定义方法`failed_attempts'代表nil:NilClass

显示/Users/neilpatel/Desktop/Rails/hangman/app/views/games/show.html.erb第3行提出

<div class="row">
      <div class="small-12 medium-4 columns">
          <div id="gallows" class="gallows gallows-state-<%= current_game.failed_attempts %>">  **<---Error**
          </div>
      </div>

class game.rb

class Game

  include ActiveModel::AttributeMethods, ActiveModel::Serializers::JSON

  class GameOverError < StandardError; end

  MAX_FAILED_ATTEMPTS = 5 

  attr_accessor :word

  attr_accessor :selected_letters


  def initialize
    @word = 'Hangman'.upcase
    @selected_letters =[]
  end

  def attributes
    {'word' => nil,
      'selected_letters' => nil}
  end

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def failed_attempts
    selected_letters.select { |letter|
      !word.include?(letter)
    }.size
  end

  def guessed?
    (word.split('') - selected_letters).empty?
  end

  def finished?
    failed_attempts >= MAX_FAILED_ATTEMPTS || !guessed?
  end

  def select!(letter)
    raise GameOverError if finished?
    selected_letters << letter unless selected_letters.include? letter word.include? letter
  end

end

游戏控制器

class GamesController < ApplicationController
  def new
    session[:current_game] = Game.new
    redirect_to game_path
  end

  def show
  end

  def update
    current_game.select! params[:letter]
    update_current_game
  rescue Game::GameOverError
    flash[:alert] = 'This game is Finished....'
  ensure
    redirect_to game_path
  end

  def destroy
    set_current_game nil
    redirect_to root_path
  end
end

application controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  helper_method :current_game

  def current_game
    @current_game ||= load_current_game
  end

  def set_current_game(game)
    @current_game = game
    session[:serialized_current_game] = game.present? ? game.to_json : nil
  end

  def update_current_game
    set_current_game @current_game
  end

1 个答案:

答案 0 :(得分:0)

我认为问题在这里......

def current_game
    @current_game ||= load_current_game
end

如果@current_game为nil,则会查找未定义的load_current_game方法。 即使你有这种方法,它也会因某种原因返回nil。