Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to only change one attribute in a model using form_for in Rails
    primarykey
    data
    text
    <p>I want to change my User model's profile attribute which is just a string in a form_for. I am running into a problem where my password is getting set to blank when I update my profile attribute.</p> <p>That is, my user account has a password, but when I change my profile, my password becomes blank. The next time I try to log in, I just leave the password field blank.</p> <p><strong>How do I change my profile field without changing my password?</strong></p> <p>Thanks.</p> <p>Here is my form below and update action. I'm passing a hidden field called updating_password which is a boolean for whether or not password validation and confirmation is required.</p> <p>edit_profile.html.erb</p> <pre><code>&lt;%= form_for @user, :html =&gt; { :multipart =&gt; true } do |f| %&gt; &lt;%= f.label :profile %&gt; &lt;%= f.text_area :profile%&gt; &lt;%= f.hidden_field :updating_password, :value =&gt; "false" %&gt; &lt;%= submit_tag "update" %&gt; &lt;% end %&gt; </code></pre> <p>users_controller.rb</p> <pre><code>def update @user = User.find(params[:id]) @user.updating_password = params[:user][:updating_password] #for updating profile only if(@user.updating_password == 'false') if @user.update_attribute('profile', params[:user][:profile]) redirect_to @user else @title = "Edit user" render 'edit' end end #for updating everything else including password if(@user.updating_password == 'true') if @user.update_attributes(params[:user]) redirect_to @user else @title = "Edit user" render 'edit' end end end </code></pre> <p>I'll add the relevant updating_password snippet from my user.rb file:</p> <pre><code>validates_presence_of :password, :if =&gt; :should_validate_password? validates_confirmation_of :password, :if =&gt; :should_validate_password? def should_validate_password? updating_password || new_record? end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload