Rails:保存子项时更新父对象

时间:2022-01-03 20:11:21

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?

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

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.

我知道:touch => true,这样做,但它也会在Message被销毁时更新Conversation,这不是我想要的。

Thanks.

谢谢。

Models

楷模

class Conversation < ActiveRecord::Base
  has_many :messages 
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

3 个解决方案

#1


38  

use callback inside Message class

在Message类中使用回调

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

#2


53  

You can just define it on the relationship as well.

您也可以在关系上定义它。

class Message < ActiveRecord::Base
  belongs_to :conversation, touch: true
end

(Source same as William G's answer: http://apidock.com/rails/ActiveRecord/Persistence/touch)

(来源与William G的答案相同:http://apidock.com/rails/ActiveRecord/Persistence/touch)

#3


9  

I prefer this solution for Rails 3:

我更喜欢Rails 3的这个解决方案:

class Message < ActiveRecord::Base
  belongs_to :conversation

  after_save :update_conversation

  def update_conversation
    self.conversation.touch
  end
end

Source: http://apidock.com/rails/ActiveRecord/Persistence/touch

资料来源:http://apidock.com/rails/ActiveRecord/Persistence/touch

#1


38  

use callback inside Message class

在Message类中使用回调

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

#2


53  

You can just define it on the relationship as well.

您也可以在关系上定义它。

class Message < ActiveRecord::Base
  belongs_to :conversation, touch: true
end

(Source same as William G's answer: http://apidock.com/rails/ActiveRecord/Persistence/touch)

(来源与William G的答案相同:http://apidock.com/rails/ActiveRecord/Persistence/touch)

#3


9  

I prefer this solution for Rails 3:

我更喜欢Rails 3的这个解决方案:

class Message < ActiveRecord::Base
  belongs_to :conversation

  after_save :update_conversation

  def update_conversation
    self.conversation.touch
  end
end

Source: http://apidock.com/rails/ActiveRecord/Persistence/touch

资料来源:http://apidock.com/rails/ActiveRecord/Persistence/touch