简体   繁体   中英

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?

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM