Chcę wymusić podanie aktualnego hasła przy edycji profilu. Aktualnie kod prezentuje się tak:
[code=ruby]class User < ActiveRecord::Base
before_create { generate_token(:auth_token) }
has_secure_password
email_regex = /\A([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})\z/i
validates_format_of :email, :with => email_regex
validates :email, presence: true
validates :name, uniqueness: true,
length: { maximum: 30 },
presence: true
validates :password_confirmation, presence: true
validates :password, presence: true
validates_length_of :password, within: 6…30
validates_uniqueness_of :name, :case_sensitive => false
validates_uniqueness_of :email, :case_sensitive => false
def generate_token(name)
self[name] = SecureRandom.urlsafe_base64
if User.exists?(name => self[name])
generate_token(name)
end
end
end[/code]
[code=ruby]class UsersController < ApplicationController
…
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.authenticate(params[:user][:current_password])
if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
params[:user][:password] = params[:user][:current_password]
params[:user][:password_confirmation] = params[:user][:current_password]
end
params[:user].delete :current_password
if @user.update_attributes(user_params)
flash[:notice] = “Zaaktalizowano profil”
redirect_to user_path @user
else
render ‘edit’
end
else
flash.now[:error] = “Nieprawidłowe hasło”
render ‘edit’
end
end
…
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end[/code]
<%= simple_form_for(@user, :html => { :class => 'form-horizontal form' }) do |f| %>
<%= f.input :name, label:"Nick" %>
<%= f.input :email, placeholder:"example@domain.com" %>
<%= f.input :current_password, label:"Aktualne hasło",
required:true %>
<%= f.input :password, label:"Nowe hasło",
hint:"Minimum 6 znaków" %>
<%= f.input :password_confirmation,
label:"Potwierdzenie", required: false %>
<%= f.button :submit, "Zatwierdź",
:class => 'btn-primary' %>
<% end %>
To rozwiązanie działa, ale jest brzydkie. W jaki sposób mogę je ulepszyć?