Topic: values dont update

i have a user but i don't want to have them update the password every time they update there info.

I have a validator that validates that the password is filled id
model

validates :password, :presence => true


What i am trying to do is not update the password if password field is nil
Controller

def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, :notice => 'User was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render :action => "edit" }
        format.json { render :json => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

Re: values dont update

Hey Moises,

Saw your question this morning but didn't know the answer. I was researching some other stuff and found a possible solution.

In the model on the validates method, do :presence => { :on => :create }

That should validate the password's presence only on the create method, so it can still be empty on the update method. I haven't tested it, but it makes sense.

Change is a vector. You can have all the change in the world, but if it doesn't go in the right direction, what good is it? | techonamission.com

Re: values dont update

Thanks that looks like it might work but i still don't have the syntax quite right


validates :password, :presence => true  :on => :create  # undefined method `key?' for nil:NilClass
 validates :password, :presence => true :create # 
 validates :password, :presence => :create # No error but but it still ask for a password that cant be blank STRANGE 

Re: values dont update

try this:

validates_presence_of :password, :on => :create

Re: values dont update

Thanks that does work with the problem that it allows the password to be empty and and does not keep the password that is already on the system

so on update password = nil

Re: values dont update

That's happening because of the way your update action is written:

 if @user.update_attributes(params[:user])

If your form has blanks for password, then the blank passwords are being passed back to the controller in the params as blank. So you will need to re-write your controller to only update the fields if the respective params valies are not blank or not nil or something along those lines.

Re: values dont update

Hey Moises,

The code for taking out the password attribute if blank for the update method is:

if params[:user][:password].blank?
  params[:user].delete(:password)
end

You would put that above the if statement for @user.update_attributes. Hope that helps.

Change is a vector. You can have all the change in the world, but if it doesn't go in the right direction, what good is it? | techonamission.com