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
                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)
use callback inside Message class
after_save do
  conversation.update_attribute(:updated_at, Time.now)
end
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With