5

我是 Rails 新手,正在关注 Ryan Bate 关于如何制作简单身份验证系统的教程(http://railscasts.com/episodes/250-authentication-from-scratch?autoplay=true),我只是在经历它但收到此错误:`

NoMethodError in UsersController#new

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

我真的不知道这意味着什么,因为我只是一个初学者,但这些是我的文件:

用户控制器:

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

新的.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 %>

路线.rb

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

用户模型

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

我认为本教程是为 Rails 3.1 或某些版本的 rails 3 制作的。但我使用的是 Rails 3.2,这可能是问题的一部分。但由于我是初学者,我不知道发生了什么。有人可以告诉我该怎么做吗?

谢谢

4

5 回答 5

9

我有同样的问题,我的服务器的简单重启解决了它。

于 2012-06-07T21:13:17.987 回答
8

这是违规行:

validates_presence_of :password, :on => create

将其更改为

validates_presence_of :password, :on => :create

另外,查看stackoverflow在您编写问题时向您显示的建议。阅读这些建议可以避免我 95% 的问题。

更新

还有一条线

<%= form for @user do |f| %>

应该

<%= form_for @user do |f| %>

现在请去三重检查您是否按应输入的所有代码:)

于 2012-03-31T02:51:30.993 回答
1
  def encrypt_password
    if password.present?
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secrete(password, password_salt)
end

您还忘记为 if 语句添加结尾。它应该是

  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
于 2012-08-03T17:48:35.983 回答
1

您在用户模型中的代码在密码上有错字。

self.password_hash = BCrypt::Engine.hash_secrete(password, password_salt)

它应该是

self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
于 2012-03-31T12:25:53.993 回答
0

我已经通过默认安装 3.0.x 版本的 bcrypt-ruby 解决了这个问题。在 Gemfile 上指定它:

gem 'bcrypt-ruby', '~> 3.0.0'
于 2014-04-04T13:44:36.260 回答