Created
January 6, 2015 05:51
-
-
Save baothi/3620809b6860951c4bee to your computer and use it in GitHub Desktop.
add new user
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
require 'digest' | |
class User < ActiveRecord::Base | |
validates_uniqueness_of :email | |
validates_length_of :email, :within => 5..50 | |
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i | |
validates_confirmation_of :password | |
validates_length_of :password, :within => 4..20 | |
validates_presence_of :password, :if => :password_required? | |
has_one :profile | |
has_many :articles, -> {order('published_at DESC, title ASC')}, | |
:dependent => :nullify | |
has_many :replies, :through => :articles, :source => :comments | |
before_save :encrypt_new_password | |
protected_attributes :password | |
def self.authenticate(email, password) | |
user = find_by_email(email) | |
return user if user && user.authenticated?(password) | |
end | |
def authenticated?(password) | |
self.hashed_password == encrypt(password) | |
end | |
protected | |
def encrypt_new_password | |
return if password.blank? | |
self.hashed_password = encrypt(password) | |
end | |
def password_required? | |
hashed_password.blank? || password_required? | |
end | |
def encrypt(string) | |
Digest :: SHA1.hexdigest(string) | |
end | |
end |
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 UsersController < ApplicationController | |
before_action :set_user, only:[:show, :edit, :update, :destroy] | |
def new | |
@user = User.new | |
end | |
def create | |
@user = User.new(user_params[:user]) | |
if @user.save | |
redirect_to articles_path, noticle: 'User successfully added' | |
else | |
render action: :new | |
end | |
end | |
def edit | |
end | |
def update | |
if @user.update(user_params) | |
redirect_to articles_path, noticle: 'Updated user information successfully' | |
else | |
render action: 'edit' | |
end | |
end | |
private | |
def set_user | |
@user = User.find(params[:id]) | |
end | |
def user_params | |
params.require(:user).permit(:email, :password, :password_confirmation) | |
end | |
end |
thay dòng protected_attributes :password
với attr_accessor :password
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
một số dòng bị sai:
redirect_to articles_path, noticle: 'Updated user information successfully'
, phải lànotice:
mới đúng