Rails:保存子对象时更新父对象 [英] Rails: Update parent object when saving child

查看:54
本文介绍了Rails:保存子对象时更新父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,一个对话有很多消息.创建/保存该对话中的新消息时,如何更新该对话的 updated_at 属性?

In my app, a Conversation has many Messages. How to I update the updated_at attribute of a Conversation when a new Message in that Conversation is created/saved?

我知道 :touch =>真的,这样做了,但是当消息被销毁时它也会更新Conversation,这不是我想要的.

I'm aware of :touch => true, which does this, but it also updates Conversation when a Message is destroyed, which is not what I want.

谢谢.

模型

class Conversation < ActiveRecord::Base
  has_many :messages 
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

推荐答案

在 Message 类中使用回调

use callback inside Message class

after_save do
  conversation.update_attribute(:updated_at, Time.now)
end

这篇关于Rails:保存子对象时更新父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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