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">
This makes sense, beacause Order
it not touched; the foreign key lives on the LineItem
.
However, in this case, I'd like to query the Order
and find only Order
s that have recieved new LineItem
s in the last 30 minutes (i.e: were "updated" in the last 30 minutes).
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?
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?