Nick Res
Nick Res

Reputation: 2244

update_attributes isn't saving to the database

The correct custom params are being displayed in my debug function after the form is submitted but the default params are displayed when I enter console.

Controller

def update
    current_user.update_attributes(params[:user])
    flash[:success] = "Your settings have been saved!"
    render new_status_update_path
end                                         

Model

attr_accessible :deficit_pct,
              :target_bf_pct,
              :activity_factor

Notes:

Any ideas?

Thanks!

Upvotes: 3

Views: 6315

Answers (4)

G SubbaRao
G SubbaRao

Reputation: 446

Try the code :-

def update
    if current_user.update_attributes(params[:user])
        flash[:success] = "Your settings have been saved!"
        render new_status_update_path
    else
        p 111111111111
        p  current_user.errors.inspect
    end
end

after check your log for any errors.exist for that active record

Upvotes: 4

Nick Res
Nick Res

Reputation: 2244

After playing around with in the console I've found out that even if I change the attributes manually the attributes don't 'stick' after I exit the console.

So I'll enter console, change the users attributes, test them, and they'll be changed. If I exist and re-enter, THEN test them, they'll have reverted back to their default values.

This leads me to believe that the 'after_initialize' method within the user model which sets its default values is running after each save. I though that it would only run after the object had been saved for the first time alone but now I know it run each time it is saved.

after_initialize :default_values 

def default_values
  self.goal = "Cut"
  self.measurement = "US"
  self.bmr_formula = "katch"
  self.fat_factor = 0.655
  self.protein_factor = 1.25 
  self.deficit_pct = 0.10
  self.target_bf_pct = 0.10
  self.activity_factor = 1.3
end

Once I remove all these values and the after_initialize method, it saves permanently.

Upvotes: 3

heartpunk
heartpunk

Reputation: 2275

Something like:


def update
    if current_user.update_attributes(params[:user])
        flash[:success] = "Your settings have been saved!"
        render new_status_update_path
    else
        some_error_handling_code
    end
end

Would not display success when the save fails. As a general rule, you should check whether a save, or any other back end operation, fails, before reporting success to the end user.

Upvotes: 1

Yves Senn
Yves Senn

Reputation: 1996

You should make sure that you don't have any validation errors. You can check them using:

active_record_model.errors

In your case, it would be

current_user.errors

Also, you should print the return value from update_attributes to see if it's true or false. If you get false, the save was cancelled. This was most likely caused by validation errors or a callback returning false.

Upvotes: 1

Related Questions