Challenge 2: Broadcasting on Create — Solution # app/models/notification.rb class Notification < ApplicationRecord belongs_to :user after_create_commit :broadcast_notification private def broadcast_notification NotificationsChannel.broadcast_to(user, NotificationSerializer.new(self).as_json) end end =begin Notes: - after_create_commit (not after_create) waits until the surrounding database transaction actually commits before broadcasting -- matching the chapter's warning: broadcasting on after_create risks telling a client about a record a later rollback then undoes. - broadcast_to(user, ...) targets exactly the stream Challenge 1's NotificationsChannel opened via stream_for current_user -- the same user object is used on both the subscribing and broadcasting side, which is what makes them the same stream. - NotificationSerializer.new(self).as_json reuses a serializer the same way rails2-5's chapter reused CommentSerializer for both the JSON API and the broadcast payload -- one definition of "what a notification looks like," regardless of which channel (HTTP or WebSocket) delivers it. =end