问题描述
我对 rails 有点陌生,我正在尝试创建一个用户登录.我浏览了此处的教程.最后它让我添加attr_accessible"进行批量分配.但是,当我这样做时,出现以下错误:
I am somewhat new to rails and I am trying to create a User login. I went through the tutorial found here. At the end it had me add "attr_accessible" for mass assignment. However when I did that I got the following error:
undefined method `attr_accessible' for #<Class:0x007ff70f276010>
我在这个帖子上看到了我需要 <活动记录::基础.但我确实包括在内.这是我的用户模型的代码:
I saw on this post that I neeed < ActiveRecord::Base. But I do have that included. Here is the code for my User Model:
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
对于可能导致此问题的任何其他想法,我们将不胜感激,谢谢!
Any other ideas on what could be causing this problem would be really appreciated, thanks!
在 Rails 4.1 上.好像已经不适用了.谢谢fotanus
On Rails 4.1. Looks like it doesn't apply anymore. Thanks fotanus
推荐答案
Rails 4.1 不允许批量赋值
No mass assignment allowed for Rails 4.1
不要在模型中使用 attr_accessible :username, :email, :password, :password_confirmation
,而是使用 强参数.您将在您的 UsersController 中执行此操作:
instead of having attr_accessible :username, :email, :password, :password_confirmation
in your model, use strong parameters. You'll do this in your UsersController:
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
然后在您的控制器操作中调用 user_params 方法.
then call the user_params method in your controller actions.
这篇关于未定义的方法 attr_accessible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!