创建新用户时的 ActiveModel::ForbiddenAttributesError [英] ActiveModel::ForbiddenAttributesError when creating new user

查看:62
本文介绍了创建新用户时的 ActiveModel::ForbiddenAttributesError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this model in Ruby but it throws a 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].

你能告诉我如何摆脱这个错误或建立一个正确的用户注册表吗?

Can you please tell me how to get rid of this error or establish a proper user registration form?

推荐答案

我猜你正在使用 Rails 4.如果是这样,必须将所需的参数标记为必需.

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

你可能想这样做:

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

这篇关于创建新用户时的 ActiveModel::ForbiddenAttributesError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆