简体   繁体   English

Rails-将另一个对象的控制器的db字段设置为null

[英]Rails - set a db field to null from another object's controller

I am attempting to set a Cabinet's Device's attributes to null in a disconnect method. 我试图在断开连接方法中将机柜的设备属性设置为null。 cabinets_controller calls @cabinet.devices.destroy(@device) and that works ok. cabinets_controller调用@cabinet.devices.destroy(@device) ,它可以正常工作。 Before I do that I want to set @device.row_id = nil and @device.position = nil . 在此之前,我想设置@device.row_id = nil@device.position = nil They are both Fixnum and attr_accesible in the Device model. 它们在设备模型中都是Fixnum和attr_accesible。 They are not being altered in the DB when I call this method. 当我调用此方法时,它们不会在数据库中更改。 Is there a method to call on @device to make this happen? 有没有一种方法可以调用@device来实现这一目标?

Thanks. 谢谢。

I'm guessing that you're trying to break the connection between a @cabinet and a @device without completely deleting the @device. 我猜您正在尝试断开@cabinet和@device之间的连接,而没有完全删除@device。 If you're already sure that @device belongs to @cabinet, it might be more straightforward to do something like: 如果您已经确定@device属于@cabinet,则执行以下操作可能会更简单:

@device.row_id = nil
@device.position = nil
@device.cabinet_id = nil
@device.save!

Basically you'll need to call .save or .save! 基本上,您需要调用.save或.save! on @device after setting those other fields to nil; 将其他字段设置为nil后,在@device上; while you're at it you may as well set cabinet_id that way, too. 当您使用它时,也可以用这种方式设置cabinet_id。

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

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