Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 887
alste Avatar asked Jul 18 '11 16:07

alste


3 Answers

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)

like image 188
chug2k Avatar answered Nov 11 '22 16:11

chug2k


use callback inside Message class

after_save do
  conversation.update_attribute(:updated_at, Time.now)
end
like image 20
Anatoly Avatar answered Nov 11 '22 15:11

Anatoly


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

like image 10
William Wong Garay Avatar answered Nov 11 '22 14:11

William Wong Garay