Last active
December 11, 2015 08:19
-
-
Save Nosfheratu/4572513 to your computer and use it in GitHub Desktop.
Creating a simple User model with secure password and image profile (gravatar)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To use ActiveModel has_secure_password | |
gem 'bcrypt-ruby', '~> 3.0.0' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Un-comment the 'bcrypt-ruby' gem in generated Rails Gemfile | |
2. Generate the User model | |
$ rails generate model User name username email password_digest avatar_url | |
3. Edit user.rb model file to add set model attributes that can be set via mass-assignment, add 'has_secure_password' helper method, another methods and some model validations | |
Thats it, Happy Codding!!! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
attr_accessible :avatar_url, :email, :name, :password, :password_confirmation, :username | |
has_secure_password | |
before_validation :prep_email | |
before_save :create_avatar_url | |
validates :name, presence: true | |
validates :username, uniqueness: true, presence: true | |
validates :email, uniqueness: true, presence: true, format: { with: /^[\w.+-]+@([\w]+.)+\w+$/ } | |
def create_avatar_url | |
self.avatar_url = "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(self.email)}?s=50" | |
end | |
private | |
def prep_email | |
self.email = self.email.strip.downcase if self.email | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment