【问题标题】:Rails password can't be blank errorRails 密码不能为空错误
【发布时间】:2015-01-21 00:08:33
【问题描述】:

我正在尝试在 Rails 4.1.6 中创建用户注册表单。我不断收到“密码不能为空”错误。我可以看到密码和密码确认都在 params 哈希中,但不在 params[:user] 子哈希中。我无法弄清楚为什么我的生活。任何帮助将不胜感激。

用户模型:

class User < ActiveRecord::Base

    belongs_to :company

    has_secure_password

end

用户控制器:

class UsersController < ApplicationController

    respond_to :json

    def index
        @users = User.all
        respond_with(@users)
    end

    def create
        @user = User.new(user_params)
        @user.save
        respond_with(@user)
    end


    private

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

end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    听起来您的参数没有正确发送到服务器。

    password 应以user[password] 发送,password_confirmation 应以user[password_confirmation] 发送。

    请参阅hash and array parameters 的文档。

    或者,将wrap_parameters 添加到控制器会将参数包装到嵌套哈希中。

    wrap_parameters :user, include: [:given_name, :family_name, :email, :password, :password_confirmation]

    请参阅ActionController::ParamsWrapper 的文档。

    【讨论】:

    • 文档有所帮助。我必须将以下内容添加到我的用户控制器中:wrap_parameters :user,包括:[:given_name, :family_name, :email, :password, :password_confirmation]。有用!感谢您的帮助!
    • 很好,我不知道wrap_parameters。我更新了我的答案以包含它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2015-02-02
    • 2017-12-07
    • 2014-09-06
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多