37
votes

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?

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.

Thanks.

Models

class Conversation < ActiveRecord::Base
  has_many :messages 
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end
3

3 Answers

68
votes

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)

42
votes

use callback inside Message class

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

I prefer this solution for 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