2

I am receiving ajax data in a rails controller. my :updatedFunds comes in within the params, and I set the users' dollars column value equal to it's value-- but it isnt persisting!

def update_dollars
    @user = User.find(params[:user_id])
    new_dollars = params[:updatedFunds]
    @user.dollars = new_dollars.to_i

    #store to database?
end

Whats the last step here?

GroundBeesAhh
  • 133
  • 1
  • 4
  • 11

3 Answers3

7
def update_dollars
    @user = User.find(params[:user_id])
    new_dollars = params[:updatedFunds]
    @user.dollars = new_dollars.to_i

    @user.save #store to database!
end
0

There are two methods that will work.

@user.update(dollars: new_dollars.to_i)

will change the attribute and record the change in the database.

You can also change it using the ruby setter method and then save to the database such as in the solution from @agripp. Both use ActiveRecord, an object-relational-mapper that Ruby on Rails just loves. The docs on it are awesome if you want to take a look.

The Brofessor
  • 2,371
  • 17
  • 13
0

you can use @user.save or if you use @user.save! then an exception will be raised it the save failed (eg. if validation failed)

ChrisW
  • 332
  • 3
  • 7