Ruby on Rails Tutorial: How to edit user information without confirming the password

戏子无情 提交于 2020-01-02 05:32:26

问题


I've been working through the Ruby on Rails Tutorial by Michael Hartl. Currently, in order to edit any of the User attributes, the user must confirm their password. Is there any way to update the user attributes without having to do this?

My form looks like this:

    <%= form_for @user do |f| %>
      <div class="field">
        <%= f.label :course1 %><br />
        <%= f.text_field :course1 %>
      </div>
      <div class="actions">
        <%= f.submit "Update" %>
      </div>
    <% end %>"

and my update definition in users_controller.rb looks like this:

def update

    if @user.update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
    else
        @title = "Edit user"
        render 'edit'
    end
end

Currently, the update_attributes action fails.

Thanks!


回答1:


On your User model, you probably have something along the lines of:

validates_presence_of :password_confirmation

Add an if clause as follows, that way it only checks for the confirmation when the password is actually being changed:

validates_presence_of :password_confirmation, :if => :password_changed?



回答2:


To slightly refine Dylan's answer, you need to define that password_changed method which was giving you the error. I used a different name, as I don't care if the password has been changed.

 validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 },
                       :unless => :already_has_password?

  private

    def already_has_password?
      !self.encrypted_password.blank?
    end



回答3:


If you are using bcrypt to encrypt the password, here is the code that worked for me on Rails 4

#--Code for User method
validates :password, presence: true, confirmation: true, :unless => :already_has_password?   
#
private
    def already_has_password?
      !self.password_digest.blank?
    end


来源:https://stackoverflow.com/questions/7073720/ruby-on-rails-tutorial-how-to-edit-user-information-without-confirming-the-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!