alste
alste

Reputation: 1455

Rails: Update parent object when saving child

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

Upvotes: 38

Views: 16676

Answers (3)

chug2k
chug2k

Reputation: 5220

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)

Upvotes: 71

William Wong Garay
William Wong Garay

Reputation: 1941

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

Upvotes: 10

Anatoly
Anatoly

Reputation: 15530

use callback inside Message class

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

Upvotes: 42

Related Questions