Search code examples
authenticationruby-on-rails-3.1update-attributes

rails update_attributes


My user model has

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

and my update action on the user's controller is

def update
        @user = User.find(params[:id])
        if @user.update_attributes(params[:user])
            flash[:success] = "Profile updated."
            redirect_to @user
        else
            @title = "Edit user"
            render 'edit'
        end
    end

my edit view is

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', :object => @user.errors%>
<div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
</div>
<div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
</div>
<div class="field">
    <%= f.label :password %> <br />
    <%= f.password_field :password %>
</div>
<div class="field">
    <%= f.label :password_confirmation, "Confirmation" %> <br />
    <%= f.password_field :password_confirmation %>
</div>
<div class="actions">
    <%= f.submit "Update" %>
</div>

The problem is that I'd like to update only specific attributes of the model, and not input the password everytime. If I don't input a password (and a confirmation) I get the validation error)

How do I fix the situation?


Solution

  • Try next validation rule

    validates :password, :presence => true, :if => lambda { new_record? || !password.nil? }