开发者

How can I update only a single field of a user profile in Rails 3?

开发者 https://www.devze.com 2023-03-26 12:24 出处:网络
I\'m adapting the authentication system from Rails 3 Tutorial by Michael Hartl to better learn about rails before (most likely) switching to a system like authlogic or devise. My authentication system

I'm adapting the authentication system from Rails 3 Tutorial by Michael Hartl to better learn about rails before (most likely) switching to a system like authlogic or devise. My authentication system works great, and I have a user model that now includes fields that build a user profile. For example, users can write a blurb about themselves such as "tennis player, rock climber".

What I'd like to do is to be able to have a simple form that updates only that specific field ("blurb"). I've set this up on a user profile page where the user clicks a link called "edit" and this causes a partial to render showing a form with a field to update a user blurb as such:

in _edit_blurb.html.erb:

 <div class = "editforms">
 <%= form_for current_user do |f| %>
<div class="field">
    <%= f.text_field :blurb, :class => "inputform round", :placeholder => "blurb" %>
</div>
<div class="actions">
    <%= f.submit "Update", :class => "submit_button round mini_button" %> <br>
</div>
 <% end %>
 </div>

This form submits to an update action in the users controller, and for the most part updates the user blurb and nothing else. However, one glitch is that this update action submits a nil password (as there is no password field in the form) - leading to a change in the user password. This is problematic for obvious reasons. Originally, I added a line :if => lamdba {new_record? || !password.nil? } to the password validation to allow the update from the edit_blurb partial 开发者_如何转开发to update without needing a password. But, as you can see this allows for a nil password to be saved.

  validates :password, :presence => true,
                    :if => lambda{ new_record? || !password.nil? },
                    :confirmation => true,
                    :length => { :within => 6..40 }

How can I alter either the form or the validation (or both) so that a user can update a blurb without updating/inputting his password (and fixing the reset-to-nil password update problem)?

I think I've provided the relevant code, but will add more if it will help! Thanks everyone!


what you'll want to do is prevent the user model from saving the password when the password value is nil. I don't know how your user model is set up, but if you've been following MH's railstutorial, the password should be saved by a method called:

   before_save :encrypt_password

in User.rb. To fix this, add:

    before_save :encrypt_password, :if => lambda { !password.nil? }

This should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消