可以使用 rails 3 访问 attr_accessor [英] Can access attr_accessor with rails 3

查看:36
本文介绍了可以使用 rails 3 访问 attr_accessor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型顶部声明了 attr_accessor :password

I declared attr_accessor :password in the top of my model

那么,我试着去做

validates :password, :presence => true, :length => { :minimum => 6 }, :if => (password.present? or hashed_password.blank?)

但它抛出异常并说 ruby​​ 不知道密码字段

But it throw exception and says that ruby don't know password field

为什么?

    class User < ActiveRecord::Base
  attr_accessor :password

  attr_accessible :name, :email, :password

  validates :name, :presence => true, :uniqueness => true
  validates :email, :presence => true
  validates :password, :presence => true, :length => { :minimum => 6 }, :if => (password.present? or hashed_password.blank?)

  before_save :encrypt_password



    def encrypt_password
      if password.present?
        self.salt = BCrypt::Engine.generate_salt
        self.hashed_password = BCrypt::Engine.hash_secret(password, salt)
      end
    end

end

推荐答案

attr_accessible 无关 - 这里的问题是你在类中调用 passwordvalidates 类方法的上下文,所以它没有在那里定义.

Nothing to do with attr_accessible - the problem here is that you're calling password in the class context of the validates class method, and so it's not defined there.

您需要提供一个 lambda,Rails 会将正在验证的实例传递给它:

You need to provide a lambda which Rails will pass the instance being validated to:

:if => lambda { |u| u.password.present? or u.hashed_password.blank? }

这篇关于可以使用 rails 3 访问 attr_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆