gpt4 book ai didi

ruby-on-rails - 创建新用户时 ActiveModel::ForbiddenAttributesError

转载 作者:行者123 更新时间:2023-12-03 04:08:23 25 4
gpt4 key购买 nike

我在 Ruby 中有这个模型,但它抛出一个 ActiveModel::ForbiddenAttributesError

class User < ActiveRecord::Base
attr_accessor :password
validates :username, :presence => true, :uniqueness => true, :length => {:in => 3..20}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, :uniqueness => true, format: { with: VALID_EMAIL_REGEX }

validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create

before_save :encrypt_password
after_save :clear_password

def encrypt_password
if password.present?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password= BCrypt::Engine.hash_secret(password, salt)
end
end

def clear_password
self.password = nil
end
end

当我运行此操作时

  def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "You Signed up successfully"
flash[:color]= "valid"
else
flash[:notice] = "Form is invalid"
flash[:color]= "invalid"
end
render "new"
end

基于ruby 1.9.3p194(2012-04-20 修订版 35410)[x86_64-linux]

您能告诉我如何消除此错误或建立正确的用户注册表单吗?

最佳答案

我猜您使用的是Rails 4。如果是这样,则必须将所需的参数标记为必需。

你可能想这样做:

class UsersController < ApplicationController

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

private

def user_params
params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
end
end

关于ruby-on-rails - 创建新用户时 ActiveModel::ForbiddenAttributesError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17335329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com