ruby-on-rails - 有没有办法获得相关模型的最后更新?
问题描述
我有Car
模型,它与许多其他模型相关联。如何检查所有关联模型的 updated_at 并获取它们中的最新版本,例如:
车门在“此时”更新
我的模型中有很多关联,因此获取每个关联并进行比较效率不高。如果有更好的方法请告诉我。谢谢。
解决方案
您可以在这里使用触摸方法。基本上,触摸用于更新updated_at
记录的字段。例如,Car.last.touch
将updated_at
最后一条记录的字段设置Car
为当前时间。
但是,touch
也可以与关系一起使用,以触发touch
关联对象上的方法。所以,在你的情况下,这样的事情可能会起作用:
class Car < ActiveRecord::Base
belongs_to :corporation, touch: true
end
class Door < ActiveRecord::Base
belongs_to :car, touch: true
end
# Door updation triggers updated_at of parent as well
@door = Door.last
@door.updated_at = DateTime.now
@door.save! # Updates updated_at of corresponding car record as well
在上面的例子中,@door.touch
也可以用来更新updated_at
对应的父Car
记录。
推荐阅读
- time-complexity - 2个嵌套循环的时间复杂度
- python-3.x - 在引发前面的异常时捕获由“finally”引起的异常
- database - 是否有可以操作布尔值的数据库
- java - 测试时没有匹配的bean,但在服务器上完美运行
- php - Getting Column not found Error at Illuminate\Database\QueryException?
- docker - docker run 中的卷和 dockerfile 中的 COPY 的差异
- javascript - 有没有办法通过 Pixi.js 画一个环?
- rust - rust 中的“match ref”是什么意思?
- laravel - Laravel 安排推送通知并在必要时取消它
- react-native - 如何在 React Native 中使用 TouchableNativeFeedback 制作下图所示的样式?