0

I don't know if there's something wrong in my code, logic, or some limitation with turbo.

I have 4 columns of divs with id="period_x" where x is the period number. Under each are scheduled courses defined by <div id=<%= dom_id(scheduled_course)%> draggable="true">

note: Screen shot does not show the form f

I am successfully able to create a new scheduled course and have it append to the correct period using turbo_stream with the following line in my scheduled_courses_controller.rb #create:

format.turbo_stream { render turbo_stream: turbo_stream.append(@scheduled_course.param_period, partial: "scheduled_courses/scheduled_course", locals: { scheduled_course: @scheduled_course }) }

note: @scheduled_course.param_period returns "period_x" where x is the period of the ScheduledCourse.

I created a stimulus controller where I can successfully, drag a scheduled course into a different period and the database updates successfully, but I only see the update when I refresh my browser.

My #update has the line:

format.turbo_stream

which successfully calls views/layouts/scheduled_courses/update.turbo_stream.erb that has the following code:

<%= turbo_stream.remove(dom_id(@scheduled_course)) %>
<%= turbo_stream.append @scheduled_course.param_period, partial: 'scheduled_courses/scheduled_course', locals: { scheduled_course: @scheduled_course } %>

Since the ScheduledCourse has been updated in the database, I should be able to remove it from the dom where it currently is, and then append it again using the newly updated period. However, update.turbo_stream.erb seems to do nothing. Even if I simply try one action, it does not do anything.

Thanks in advance for taking the time to help.

Sana
  • 79
  • 1
  • 13

1 Answers1

0

Within my stimulus controller, I needed to add the line:

.then(Turbo.renderStreamMessage)

I found out that rails does this automatically for form submissions, but custom AJAX requests require it. Now the AJAX request in my stimulus controller looks like:

  fetch(`/scheduled_courses/${scheduledCourseId}`, 
    {
      method: 'PATCH',
      headers: 
      {
        'Content-Type': 'application/json',
        'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify({ target_period: target_period })
    })
    .then((response) => response.text())
    .then(Turbo.renderStreamMessage)
    .catch((error) => 
    {
      console.error('Error:', error);
    });

And now I can drag and drop between divs and my database continues to work as it should. Special thanks to Mix & Go's youtube channel where I found the solution.

Sana
  • 79
  • 1
  • 13