简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM