在rails 4应用程序上使用安全密码

时间:2014-03-17 10:14:51

标签: ruby-on-rails ruby ruby-on-rails-4 bcrypt-ruby

我尝试使用has_secure_password进行用户登录,我已将用户模式定义如下

require 'digest/md5'

class User < ActiveRecord::Base

    has_secure_password
    before_validation :prep_emailId
    before_save :create_avatar_url

    validates :emailId, presence: true, uniqueness: true, format: { with: /\A(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})\z/i }
    validates :first_name, presence: true

    has_many :projects
    belongs_to :nationality
    belongs_to :category

    scope :sorted, lambda{order("projects.position ASC")}
    scope :newest_first, lambda{ "projects.created_at DESC"}
    scope :oldest_first, lambda{order("projects.created_at ASC")}
    scope :search, lambda{|query|
        where(["name LIKE?", "%#{query}%"])
    }

    private 
    def prep_emailId
        self.emailId = self.emailId.strip.downcase if self.emailId
    end

    def create_avatar_url
        self.avatar_url = "http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest(self.emailId)}?s=50"
    end

end

我已在控制器上声明了强参数

def user_params
    params.require(:user).permit(:category_id, :nationality_id, :first_name,
        :last_name, :gender, :date_of_birth, :emailId, :password, 
        :password_confirmation, password_digest, :avatar_url)
end

这是我的创建方法。

def create
    @user = User.new(user_params)
    if @user.save
        redirect_to user_path(@user.id) 
        #notice: "Thanks you for signing up !!!"
    else
        render ('new')
    end
end

我尝试保存时遇到的错误如下

Password digest missing on new record

现在,如果我从stackoverflow上的许多人的建议中取出attr_accessor,这就是我最终得到的。

Mysql2::Error: Data too long for column 'password_digest' at row 1: INSERT INTO `users` (`avatar_url`, `created_at`, `emailId`, `first_name`, `last_name`, `password_digest`, `updated_at`) VALUES ('http://www.gravatar.com/avatar/f76ca3885ff46187f3a216ba566623b9?s=50', '2014-03-17 10:39:01', 'funny@funnier.com', 'funny', 'funnier', '$2a$10$lJp6l70lHepWGz08f4O7luT3kE6Wj7bYzqD3o6G.EErkl0FTbAiHq', '2014-03-17 10:39:01')

1 个答案:

答案 0 :(得分:1)

您不需要attr_accessors,因为has_secure_password会处理该问题并进行验证。您希望在视图中使用password_confirmation而不是密码确认。