ruby-on-rails - 未定义方法 attr_accessible

标签 ruby-on-rails ruby

我对 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/

相关文章:

ruby-on-rails - 安装多个版本的 Rails 会覆盖以前的安装吗?

ruby-on-rails - 如何制作基于时间的问候语

mysql - Rails + MySQL 中的发票编号

ruby-on-rails - 在 Rails 中使用 Sunspot 和 Solr 连接被拒绝

ruby - 如何编写仅在第一个和最后一个位置删除字符的 ruby​​ 正则表达式?

ruby-on-rails - rails : running an initializer after migrate

ruby-on-rails - 加载 'sqlite3' Active Record 适配器时出错。当我在 Heroku 中部署时

ruby-on-rails - asset_sync gem 错误:rake assets:precompile 失败:与服务器证书不匹配(OpenSSL::SSL::SSLError)

ruby-on-rails - 如何替换 Ruby 中带重音的拉丁字符?

ruby-on-rails - Rails 用户注册邮件确认