2011-03-22 59 views
1

我从Rails教程中找到的用户模型中推导出发现here以了解有关创建模型的更多信息。我试图给用户一个确认标志,该标志最初设置为false,直到用户通过点击注册后发送的自动邮件中的链接确认其身份。将Rails模型属性结果添加到RecordNotSaved错误中

在我添加确认的属性之前,所有工作都正常。我通过迁移向数据库添加了确认列,因此在我看来,错误发生在before_save :confirmed_false逻辑中的某处。

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

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

    email_regex = /\A[\w+\-.][email protected][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 
+0

你得到了什么确切的错误? – rubyprince 2011-03-22 06:48:23

回答

2

在迁移,如果你设置了证实列是一个布尔值,默认值是假的,那么你不需要before_save :confirmed_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 
+0

好吧,我知道你可以在迁移中设置默认值,所以我一定会尝试。但是如果我有另一个像registration_date这样的属性,在记录创建时需要设置它(一个属性永远不会通过构造函数设置),但是在迁移中不可能将其设置为默认值。我正在使用的逻辑为此工作? – 2011-03-22 15:05:25

+0

你可以有一个'before_create'回调。我会在上面更新我的答案。 – lebreeze 2011-03-22 15:16:11

0

真的不能找出你想在这里做什么。您似乎想要将默认值设置为confirm = false,如果用户单击适当的链接并向您发送正确的令牌或类似内容,则将其更改为confirmed = true。

所以流将是这样的:

  1. 用户记录与确认=假
  2. 没有必要对的before_filter不要做任何事情
  3. 用户执行一些操作创建允许他确认栏设置为true
  4. 仍然没有需要一个的before_filter

有什么before_filter for?你是否试图用它来设置默认值?