Rails 3 before_save不工作?

时间:2014-02-01 04:11:25

标签: ruby-on-rails

我得到这个错误undefined方法`before_save'for UsersController:Class。有没有什么特别的原因可以解决为什么未定义before_save?

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :username

  attr_accessor :password
  before_save :encrypt_password
  before_save { self.email = email.downcase}

...

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

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private

    def create_remember_token
      self.remember_token = User.encrypt(User.new_remember_token)
    end
end

1 个答案:

答案 0 :(得分:0)

无论您是否修复了错误,我都建议您将before_save操作放入一个方法(以保持干燥):

  before_save :format_data

  def format_data
      self.email = email.downcase if email.present?
      if password.present?
          self.password_salt = BCrypt::Engine.generate_salt
          self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
      end
  end