如何在新的has_many关联上使ActiveRecord bump updated_at

将记录添加到has_many关联并保存父级时,该父级的updated_at不会被碰撞:

 order = Order.new order.save pp order => # order.line_items < [#] order.save pp order.reload => # 

这是有道理的,因为Order它没有触及; 外键存在于LineItem

但是,在这种情况下,我想查询Order并找到在过去30分钟内收到新LineItemOrder (即:在过去30分钟内“更新”)。

我不确定这里最好做什么,以及如何轻松实现这一目标。 是否有一些标志或方法我可以设置让AR更新父母updated_at如描述? 或者我应该通过一些钩子来做到这一点? 如果是这样,什么挂钩? 或者我应该将此时间戳存储在不同的列中?

请注意,我可以通过join(:line_items)查询line_items.updated_at ,但这可能会使我的代码更混乱,性能更差:或者这是Rails中此类问题的首选方式?

您需要包含touch: true以及belongs_to :order association。

 class Order < ActiveRecord::Base has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :order, touch: true end 

这将更新关联订单的updated_at列。 这里有更多的文档

您可以使用触摸选项,如下所示。

 class LineItems < ActiveRecord::Base belongs_to :order, :touch => true ... end 

每当保存或销毁lineitem时,这将更新父订单的“update_at”。

引自http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html ,

:触摸

 If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. 

如果指定符号,除了updated_at / on属性之外,还将使用当前时间更新该属性。