我对rails很新,我正在尝试创建用户登录。我查看了here找到的教程。最后它让我为质量分配添加“attr_accessible”。但是,当我这样做时,我收到以下错误:
undefined method `attr_accessible' for #<Class:0x007ff70f276010>
我在post看到了我所需要的&lt;的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。看起来它不再适用了。谢谢fotanus
答案 0 :(得分:79)
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
然后在控制器操作中调用user_params方法。
答案 1 :(得分:15)
Rails 4.1不允许进行质量分配
你必须尝试这样的事情。
class Person
has_many :pets
accepts_nested_attributes_for :pets
end
class PeopleController < ActionController::Base
def create
Person.create(person_params)
end
...
private
def person_params
# It's mandatory to specify the nested attributes that should be whitelisted.
# If you use `permit` with just the key that points to the nested attributes hash,
# it will return an empty hash.
params.require(:person).permit(:name, :age, pets_attributes: [ :name, :category ])
end
end
参见