首页 > 解决方案 > 有没有办法获得相关模型的最后更新?

问题描述

我有Car模型,它与许多其他模型相关联。如何检查所有关联模型的 updated_at 并获取它们中的最新版本,例如:

车门在“此时”更新

我的模型中有很多关联,因此获取每个关联并进行比较效率不高。如果有更好的方法请告诉我。谢谢。

标签: ruby-on-rails

解决方案


您可以在这里使用触摸方法。基本上,触摸用于更新updated_at记录的字段。例如,Car.last.touchupdated_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记录。


推荐阅读