undefined method `key?' for nil:NilClass

user1302430 picture user1302430 · Mar 31, 2012 · Viewed 20.8k times · Source

I'm new to Rails and was following Ryan Bate's tutorial on how to make a simple authentication system (http://railscasts.com/episodes/250-authentication-from-scratch?autoplay=true) and I was just going through it but got this error: `

NoMethodError in UsersController#new

undefined method `key?' for nil:NilClass
Rails.root: C:/Sites/authentication`

I don't really know what this means since I'm just a beginner, but these are my files:

users controller:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
        redirect_to root_url, :notice => "Signed up!"
    else
        render "new"
    end
  end
end

new.html.erb:

    <%= form for @user do |f| %>
<% if @user.errors.any? %>
<div class="error_messages">
    <h2>Form is invalid</h2>
    <ul>
        <% for message in @user.errors.full_messages %>
        <li><%= message %></li>
        <% end %>
    </ul>
</div>
<% end %>
<p>
    <%= f.label :email %>
    <%= f.text_field :email %>
</p>
<p>
    <%= f.label :password %>
    <%= f.password_field :password %>
</p>
<p>
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>

routes.rb

    Authentication::Application.routes.draw do
  get "sign_up" => "users#new", :as => "sign_up"
  root :to => "users#new"
  resources :users
 end

user model

class User < ActiveRecord::Base
    attr_accessor :password
    before_save :encrypt_password

    validates_confirmation_of :password
    validates_presence_of :password, :on => create
    validates_presence_of :email
    validates_uniqueness_of :email

    def encrypt_password
        if password.present?
            self.password_salt = BCrypt::Engine.generate_salt
            self.password_hash = BCrypt::Engine.hash_secrete(password, password_salt)
    end
end

I think the tutorial was made for Rails 3.1 or some version of rails 3. But I am using Rails 3.2, that might be part of the problem. But since I'm a beginner I have no idea what is going on. Could someone tell me what to do?

Thanks

Answer

tomb picture tomb · Jun 7, 2012

I had this same problem, and a simple restart of my server solved it.