I have a Conversation ActiveRecord model which is essentially the following
class Conversation < ActiveRecord::Base
has_many :messages, :order => 'created_at ASC'
belongs_to :latest_message, :class_name => 'Message'
end
I want the latest_message property to always be set to messages.last. I’ve tried the before_save callback but that doesn’t seem to get fired when I add a message like
conversation.messages.create!(
sender: user,
body: message_body
)
Any ideas?
Found the answer while I was writing the question up:
ActiveRecord association callbacks let me call a method which updates the message when necessary updated. It would be nice if I didn’t have to call save again…