如何使ActiveRecord的凹凸的updated_at新的has_many协会 [英] how to make ActiveRecord bump updated_at on new has_many association

查看:76
本文介绍了如何使ActiveRecord的凹凸的updated_at新的has_many协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将记录添加到的has_many 的关联和保存的父母,是父母的的updated_at 不碰着:

When adding records to a has_many association and saving the parent, that parent's updated_at is not bumped:

order = Order.new
order.save
pp order
  => #<Order id: 3, created_at: "2013-04-18 15:25:09", updated_at: "2013-04-18 15:25:09"> 
order.line_items << LineItem.new()
pp order.line_items
  => [#<LineItem id: 4, order_id: 3, created_at: "2013-04-18 15:26:16", updated_at: "2013-04-18 15:26:29", product_id: 123>] 
order.save
pp order.reload
  => #<Order id: 3, created_at: "2013-04-18 15:25:09", updated_at: "2013-04-18 15:25:09">

这是有道理的,东阳订单它没有触及;外键的生命在的LineItem

This makes sense, beacause Order it not touched; the foreign key lives on the LineItem.

然而,在这种情况下,我想查询订单键,只找到<$​​ C $ C>订单 s表示有:收到新的的LineItem S在最后30分钟(即:被更新,在最后30分钟)。

However, in this case, I'd like to query the Order and find only Orders that have recieved new LineItems in the last 30 minutes (i.e: were "updated" in the last 30 minutes).

我不知道什么是最好的,在这里做,我怎么可以很容易地做到这一点。有一些标志或方法我可以设置有AR更新家长的updated_at 描述的一样?或者我应该这样做,通过一些挂钩?如果是这样,什么挂钩?或者我应该存储这些时间戳在不同的列?

I am not sure what is best to do here, and how I could achieve this easily. Is there some flag or method I could set to have AR update the parents updated_at like described? Or should I do this via some hook? If so, what hook? Or should I store this timestamp in a different column?

请注意,我可以查询 line_items.updated_at 海槽加入(:line_items),但这可能让我的code比较凌乱,少高性能:或者是这个preferred方式在Rails的这些问题。

Note that I could query the line_items.updated_at trough a join(:line_items), but that would probably make my code more cluttered and less performant: or is this the preferred way for such issues in Rails?

推荐答案

您需要包括摸:真以及 belongs_to的:为了的关联。

You need to include touch: true along with 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 列相关的命令。更多文档这里

This will update the updated_at column for the associated order. More docs here

这篇关于如何使ActiveRecord的凹凸的updated_at新的has_many协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆