rails update_attributes

549 views Asked by At

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?

2

There are 2 answers

0
Fivell On BEST ANSWER

Try next validation rule

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

1
Baldrick On

You can use attr_protected to exclude some fields from update_attributes. See the doc . An even better way is to use attr_accessible to white list the attributes that can be updated by mass-assignment.