Cam*_*nes 35 ruby ruby-on-rails
我对rails很新,我正在尝试创建用户登录.我浏览了这里的教程.最后它让我为质量分配添加"attr_accessible".但是,当我这样做时,我收到以下错误:
undefined method `attr_accessible' for #<Class:0x007ff70f276010>
Run Code Online (Sandbox Code Playgroud)
我在这篇文章中看到我需要<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
Run Code Online (Sandbox Code Playgroud)
关于可能导致这个问题的任何其他想法将非常感谢,谢谢!
编辑:On Rails 4.1.看起来它不再适用了.谢谢fotanus
Wal*_*Ali 81
Rails 4.1不允许批量分配
而不是attr_accessible :username, :email, :password, :password_confirmation
在您的模型中,使用强参数.您将在UsersController中执行此操作:
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
Run Code Online (Sandbox Code Playgroud)
然后在控制器操作中调用user_params方法.
Sar*_*esh 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
Run Code Online (Sandbox Code Playgroud)
参考
https://github.com/rails/strong_parameters
归档时间: |
|
查看次数: |
48687 次 |
最近记录: |