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

时间:2011-07-18 16:39:45

标签: ruby-on-rails

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

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

感谢。

模型

class Conversation < ActiveRecord::Base
  has_many :messages 
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

3 个答案:

答案 0 :(得分:56)

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

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

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

答案 1 :(得分:40)

在Message class

中使用回调
after_save do
  conversation.update_attribute(:updated_at, Time.now)
end

答案 2 :(得分:9)

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

class Message < ActiveRecord::Base
  belongs_to :conversation

  after_save :update_conversation

  def update_conversation
    self.conversation.touch
  end
end

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

相关问题