问题
I'm trying to use has_secure_password for user login, I've defined the User mode as below
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
I've declared strong parameters on the controller
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
Here's my create method.
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
The error I'm getting when I try to save is as follows
Password digest missing on new record
Now if I take out attr_accessor from this code as suggested by many on stackoverflow this is what I end up getting.
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:
You don't need the attr_accessors as has_secure_password handles that and the validation. You'll want password_confirmation in the view not password confirm.
来源:https://stackoverflow.com/questions/22451633/using-has-secure-password-on-a-rails-4-app