【发布时间】:2013-06-24 11:49:46
【问题描述】:
我在 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 revision 35410) [x86_64-linux].
您能告诉我如何消除此错误或建立正确的用户注册表单吗?
【问题讨论】:
-
尝试在用户模型中添加 attr_accessible :password, :password_confirmation,:user_name, :email, :your-other-attributes
-
添加 strong_parameter gem 以使用 attr_accessible。
-
使用attr_accessible的强参数?!
-
我相信@BruceLi 的意思是:添加
protected_attributesgem 以使用attr_accessible。
标签: ruby-on-rails rails-activerecord