【问题标题】:Rails: Password can't be blank with has_secure_passwordRails:使用 has_secure_password 密码不能为空
【发布时间】:2026-01-15 18:40:02
【问题描述】:

我正在尝试按照本教程 (Rails Tutorial by Michael Hartl) 创建一个有效用户。填写密码字段仍然给我错误“密码不能为空”和“密码必须更长,谢谢 6 个字母”。我尝试通过 rails 控制台创建用户,效果很好。只有当我尝试通过网站本身进行操作时。

我的用户模型如下所示:

class User < ApplicationRecord
  #before saving, make sure the email is in downcase
  before_save { self.email = email.downcase }

  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: {case_sensitive: false}

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
end

我的 user_controller 看起来像这样:

class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
#wrap_parameters :user, include: [:name, :email, :password, :password_confirmation]

def index
  @users = User.all
end

def show
  @user = User.find(params[:id])
  #debugger
end
def new
  @user = User.new
end

# GET /users/1/edit
def edit
end

#POST /users
#POST /users.json
def create
  @user = User.new(user_params) #params[:user])#user_params)

  respond_to do |format|
    if @user.save
      #flash[:success] = "Welcome to CourseBuddies!"

      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
      redirect_to @user
    else
      #render 'new'
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /users/1
# DELETE /users/1.json
def destroy
  @user.destroy
  respond_to do |format|
    format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    format.json { head :no_content }
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:name, :email, :pasword, :password_confirmation)
  end
end

这是我的迁移文件 create_user:

class CreateUsers < ActiveRecord::Migration[5.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email
     t.string :password
     t.string :password_confirmation

     t.timestamps
   end
 end

结束

我尝试了网上找到的不同解决方案,例如使用“wrap_parameters”,但它似乎对我没有任何作用。

我的 Gemfile 看起来像这样:

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
gem 'bootstrap-sass', '3.3.7'
# make pw digest "has_secure_password" use a stateofart hash function (bcrypt)
gem 'bcrypt', '3.1.11'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.4'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more:     https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3', '1.3.13' #railsTuto said to get this, but already use postgresql
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'rails-controller-testing', '1.0.2'
  gem 'minitest-reporters',       '1.1.14'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '~>0.18.4'
  gem 'rails_12factor'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

编辑:我的表格

<%- #FIELDS FOR THE FORM %>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user, url: signup_path) do |f| %>

    <%- #ERROR MESSAGES %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <br>
    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <br>  
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <br>  
    <%= f.label :password_confirmation, "Confirmation" %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>


    <br><br>
    <%= f.submit "Create my account", class: "btn btn-primary" %>
  <% end %>
</div>

如果能提供任何帮助或澄清,我将不胜感激。谢谢!

【问题讨论】:

  • 用表单代码更新问题。
  • 我看到你在user_params 中有pasword 而不是password。是那个错字吗?或者你真的有这样的吗?如果你有这样的,那么这就是错误的原因。
  • 可以用遇到错误时生成的日志更新问题吗?
  • 好的,所以我修正了我的错字。我现在可以报名了!我的错误似乎是错字。而且,我的登录似乎也正常工作!
  • 很高兴听到!那么你应该将我的答案标记为已接受:)

标签: ruby-on-rails ruby passwords c9.io


【解决方案1】:

解决方案:

好的,所以在修复了我的控制器中的错字之后(由@Pavan 指出),我还删除了我的用户模型(@Divya Sharma)中的存在:true,所以它看起来像这样:

validates :password, length: { minimum: 6 }, allow_nil: true

我现在可以正确注册我的用户并登录!

我认为输入“allow_nil:true”实际上只是让我注册,因为不知何故,我的 password_fields 仍然是“nil”。我想那是因为我的错字的错。无论如何,谢谢你们这么快!

【讨论】:

    【解决方案2】:

    错误的实际原因是您在user_params错误输入 passwordpasword。修正错字应该可以解决您的问题。

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end
    

    【讨论】:

      【解决方案3】:

      我认为您需要在验证中添加 allow_nil: true

      validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
      

      as allow_nil: true 不允许创建空字符串。

      【讨论】:

      • @Sedad.Kosovac has_secure_password 自动添加存在和确认检查
      • @Myth 你可以从验证中删除 presence: true ,因为 has_secure_password 会处理它,所以你的代码会是这样的: validates :password, length: { minimum: 6 }, allow_nil: true 跨度>
      • 我认为错字是我的错误!它现在可以正常工作:)(不使用allow_nil:true)。谢谢大家!