简体   繁体   English

Rails从另一个控制器保存模型属性

[英]Rails save model Attribute from another Controller

I would like to change a value for a 'device' model from my User controller. 我想通过用户控制器更改“设备”模型的值。 Currently I get the device then set the value, but it isn't saving the value to the device. 目前,我得到了设备,然后设置了值,但是它没有将值保存到设备中。 How do I get it to save? 我如何保存它? thanks 谢谢

User controller.rb 用户controller.rb

      @device = @user.device
      @device.lastUpdated = Time(now)

To save the changes to your database, you can use the save method. 要将更改保存到数据库,可以使用save方法。 Try using @device.save after you update the attribute. 更新属性后,尝试使用@ device.save。

  @device = @user.device
  @device.lastUpdated = Time(now)
  if @device.save
    # do something when save is successful
  else
    # handle the case when it doesn't save properly
  end

Edit: Take a look at the list of persistence methods in the Rails documentation (ie these are methods that will write information to the database). 编辑:查看Rails文档中的持久性方法列表(即,这些方法会将信息写入数据库)。

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

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