My User model is using has_secure_password (based on the Rails tutorial Book):
schema.rb:
create_table "users", :force => true do |t|
t.string "password_digest"
end
user.rb:
class User < ActiveRecord::Base
attr_accessible :name, :email, :avatar, :password, :password_confirmation, :provider, :uid
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
And I have this edit view:
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirm Password" %>
<%= f.password_field :password_confirmation %>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
Now the problem is that the user has to fill the password and password_confirmation field each time he/she wants to update the other fields.
So I was thinking of dividing the form:
users/edit.html.erb:
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :avatar %>
<%= f.file_field :avatar %>
users/edit_password:
(I will add a current_password field later here).
<%= f.label :password, "New Password" %>
<%= f.password_field :password, %>
<%= f.label :password_confirmation, "Confirm Password", "Retype Password" %>
<%= f.password_field :password_confirmation %>
I’m thinking of two options:
- Having all the user fields in each view, but making those fields I don’t want the user to see hidden fields (the problem is that I can’t retrieve the password for some reason. Something like
@user.passwordreturnsnil. I can only do@user.password_digestbut that won’t validate the field). - Adding
:unlessin thepasswordandpassword_confirmationvalidation (but I’m not sure how to do it so that it only applies to theusers/editview).
What’s the best solution here?
You cannot get user’s password since the DB does not store it (it stores one-way encrypted password digest). So the second option is correct.
Take a look at Devise implementation (validation and controller), it can help.