添加Rails模型属性会导致RecordNotSaved错误

时间:2011-03-22 06:32:44

标签: ruby-on-rails ruby model

我从Rails教程中给出的用户模型推断here,以了解有关创建模型的更多信息。我试图给用户一个确认标志,该标志最初设置为false,直到用户通过点击注册后发送的自动电子邮件中的链接确认其身份。

在添加确认属性之前,一切正常。我通过迁移向数据库添加了一个已确认的列,因此在我看来错误发生在before_save :confirmed_false逻辑中的某个位置。

有人能帮助我吗?用户模型如下。

class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :email, :password, :password_confirmation

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name,  :presence => true,
                    :length   => { :maximum => 50 }

  validates :email, :presence   => true,
                    :format     => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false }

  validates :password,  :presence     => true,
                        :confirmation => true,
                        :length       => { :within => 6..40 }

  before_save :encrypt_password
  before_save :confirmed_false

  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil if user.nil?
    return user if user.has_password?(submitted_password)
  end

  private

    def confirmed_false
      self.confirmed = false if new_record?
    end

    def encrypt_password
      self.salt = make_salt if new_record?
      self.encrypted_password = encrypt(password)
    end

    def encrypt(string)
      secure_hash("#{salt}--#{string}")
    end

    def make_salt
      secure_hash("#{Time.now.utc}--#{password}")
    end

    def secure_hash(string)
      Digest::SHA2.hexdigest(string)
    end
                                                              1,1           Top

2 个答案:

答案 0 :(得分:2)

在迁移中,如果将确认列设置为布尔值并将默认值设置为false,则根本不需要before_save :confirmed_false回调,因为当它是新记录时始终为false

<强>更新

class User < ActiveRecord::Base
  # unlike before_save it's only run once (on creation)
  before_create :set_registration_date

  def set_registration_date
    registration_date = Time.now # or Date.today
  end
end

答案 1 :(得分:0)

无法弄清楚你在这里要做什么。您似乎要将默认值设置为confirm = false,如果用户单击相应的链接并向您发送正确的令牌或类似内容,则将其更改为confirm = true。

所以流程将是这样的:

  1. 使用confirm = false
  2. 创建用户记录
  3. 没有必要在before_filter做任何事情
  4. 用户执行一些操作以允许将已确认的列设置为true
  5. 仍然不需要before_filter
  6. before_filter是什么?您是否尝试使用它来设置默认值?

相关问题