简体   繁体   English

如何在Rails控制器中将数据“保存”到数据库?

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

I am receiving ajax data in a rails controller. 我正在Rails控制器中接收Ajax数据。 my :updatedFunds comes in within the params, and I set the users' dollars column value equal to it's value-- but it isnt persisting! 我的:updatedFunds包含在参数中,并且我将用户的dollars列值设置为等于它的值,但是它并不持久!

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. 您也可以使用ruby setter方法更改它,然后将其保存到数据库中,例如@agripp中的解决方案中。 Both use ActiveRecord , an object-relational-mapper that Ruby on Rails just loves. 两者都使用ActiveRecord ,这是Ruby on Rails所喜欢的对象关系映射器。 The docs on it are awesome if you want to take a look. 如果您想看看它的文档很棒。

you can use @user.save or if you use @user.save! 您可以使用@ user.save或使用@ user.save! then an exception will be raised it the save failed (eg. if validation failed) 那么保存失败(例如,验证失败)将引发异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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