1

I have a Rails 7 application with a "Workout" form. Once I submit the form, I have two callbacks that execute.

The first is the after commit on the Workout model. This finds/updates or creates a WorkoutSummary record. The second is the after create commit callback on WorkoutSummary to broadcast an broadcast_prepend_later_to a page that displays all workout_summary records.

Currently, if I open up two browser windows and I put one of the page the broadcast is targeting, it updates when the form submits. The other browser window that I use to type in the form and submit, redirects_to the same page the other browser window has open. The only problem is the new record doesn't always show up. I'm guessing the page is reloading before the new record exists, but after the broadcast has already gone out.

My question is how should I handle this so that I can see the new record after submitting the form and being redirected to the page?

workout.rb

class Workout < ApplicationRecord
  include Destroyable
  
  has_one :workout_summary, dependent: :delete

  after_commit :recalculate_workout_summary

  def recalculate_workout_summary
    WorkoutSummaryJob.perform_later self
  end

end

workout_summary.rb

class WorkoutSummary < ApplicationRecord
  include MeasurableCalculable, ActionView::RecordIdentifier

  belongs_to :workout

  after_create_commit :broadcast_later

  delegate :date, to: :workout, allow_nil: true
  delegate :player, to: :workout

  private
    
  def broadcast_later
    broadcast_prepend_later_to [player, :workout_summaries], target: "#{dom_id(player)}_workout_summaries", partial: "players/workouts/workout_summary", locals: { workout_summary: self }
  end

  def summarize
    recalculate_measurables(workout.measurables)
    self.save
  end

end
daveomcd
  • 6,367
  • 14
  • 83
  • 137

0 Answers0