我对 Rails 有点陌生,我正在尝试创建一个用户登录。我通过教程找到了here .最后它让我为批量分配添加“attr_accessible”。但是,当我这样做时,出现以下错误:
undefined method `attr_accessible' for #<Class:0x007ff70f276010>
我看到了这个 post我需要 < ActiveRecord::Base。但我确实包括在内。这是我的用户模型的代码:
class User < ActiveRecord::Base
attr_accessor :password
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
before_save :encrypt_password
after_save :clear_password
attr_accessible :username, :email, :password, :password_confirmation
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
对于可能导致此问题的任何其他想法,我们将不胜感激,谢谢!
编辑:On Rails 4.1。看起来它不再适用了。谢谢火神
最佳答案
Rails 4.1 不允许批量分配
不要在模型中使用 attr_accessible :username, :email, :password, :password_confirmation
,而是使用 strong parameters .
您将在您的 UsersController 中执行此操作:
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
然后在您的 Controller 操作中调用 user_params 方法。
关于ruby-on-rails - 未定义方法 attr_accessible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437830/