K
K
keri42014-07-06 21:14:29
HTML
keri4, 2014-07-06 21:14:29

How to change attributes without password using has_secure_password, Rails 4?

User model:

class User < ActiveRecord::Base  
  validates :email, presence: true, format: { with: /\A[a-z\d\-_.][email protected][a-z\d\-.]+\.[a-z]+\z/i }, uniqueness: { case_sensitive: false }
  validates :name, length: { maximum: 100 }
  validates :password, length: { minimum: 6 }
  
  before_save { email.downcase! }
  
  has_secure_password
  
  has_many :events, dependent: :destroy  
end

There are two forms on one page:
<%= form_for @user, html: { class: 'form-horizontal' } do |f| %>
    <div class = 'form-group'>
      <%= f.label 'Name', class: 'col-sm-6 control-label' %>
      <div class = 'col-sm-6'>
        <%= f.text_field :name, class: 'form-control' %>
      </div>
    </div>
    <div class = 'form-group'>
      <%= f.label 'Email', class: 'col-sm-6 control-label' %>
      <div class = 'col-sm-6'>
        <%= f.email_field :email, class: 'form-control' %>
      </div>
    </div>
    <div class = 'form-group'>
      <div class = 'col-sm-8 col-sm-offset-6'>
        <%= f.submit 'Update profile', class: 'btn btn-primary' %>
      </div>
    </div>
  <% end %>
  
  <%= form_for @user, html: { class: 'form-horizontal' } do |f| %>
    <div class = 'form-group'>
      <%= f.label 'Current password', class: 'col-sm-6 control-label' %>
      <div class = 'col-sm-6'>
        <%= f.password_field :current_password, class: 'form-control' %>
      </div>
    </div>
    <div class = 'form-group'>
      <%= f.label 'New password', class: 'col-sm-6 control-label' %>
      <div class = 'col-sm-6'>
        <%= f.password_field :password, class: 'form-control' %>
      </div>
    </div>
    <div class = 'form-group'>
      <%= f.label 'Confirm new password', class: 'col-sm-6 control-label' %>
      <div class = 'col-sm-6'>
        <%= f.password_field :password_confirmation, class: 'form-control' %>      
      </div>
    </div>
    <div class = 'form-group'>
      <div class = 'col-sm-8 col-sm-offset-6'>
        <%= f.submit 'Change password', class: 'btn btn-primary' %>
      </div>
    </div>
  <% end %>

Using the second form, it turns out to change the password, but the first form does not work, it needs the :password key in the params, #update_attributes does not work, because of this change is not recorded in the database.
I really need help, because I don't want to ask for a password when changing the name or email of the user.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Vsk, 2014-07-06
@viktorvsk

Why not a device? If there are at least some development plans, then without it it will hardly be easy.
And instead of update_attributes, as a last resort, you can use update_column

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question