GroundBeesAhh
GroundBeesAhh

Reputation: 133

How do you 'save' data to your database in a rails controller?

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?

Upvotes: 2

Views: 11424

Answers (3)

ChrisW
ChrisW

Reputation: 372

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)

Upvotes: 0

The Brofessor
The Brofessor

Reputation: 2411

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.

Upvotes: 0

user3136452
user3136452

Reputation:

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

Upvotes: 7

Related Questions