ruby-on-railshotwire-railswicked-gem

Using turbostreams in wicked wizard's "show" action?


I'm confused about the pattern someone would use to replace an item in the dom using turbo streams in combination with wicked wizard using the "show action". In my scenario, I'm trying to replace a nested turboframe "foo" that exists on step_b using the "show" action, which looks like this:

def show 
  case step

  when :step_a

  when :step_b
 
  when :step_c

  render_wizard
end

In step_b's view, I have several links, and they all link back to step b, but with different params. (I'm actually using an API call to fetch and render times in an appointment picker, and the params represent the dates for those times).

<%= link_to "Today", step_b_path(date: 03-14-23) %>

Would ideally replace the "foo" turboframe inside step_b's view with all the times for 3/14/23.

<%= link_to "Tomorrow", step_b_path(date: 03-15-23) %>

Would ideally replace the "foo" turboframe inside step_b's view with all the times for 3/15/23.

The user can keep clicking these links, which will update the appointment times, until they finally pick and submit their appointment selection for that step in the form. Once they select a time and click "submit" it calls the update action and proceeds to step_c

I've seen that if I have a <%= turbo_frame_tag "foo" %> on step_a, I can create a step_b.turbo_stream.erb to replace the turboframe on step a by doing something like this:

<%= turbo_stream.replace "foo", partial: "partial_path", locals: { bar: @baz } %>

However, I'm having issues with this because it seems like this only gets called when a user "submits" and calls the update function. What I want is for the turboframe to update when they click on a link to step_b, which only calls the "show" action. The nested turbo frame I'm trying to update only exists on step_b.

However, when I try to add something like this to the show action:

when :step_b
  respond_to do |format|
    format.turbo_stream { render turbo_stream: turbo_stream.replace("foo", partial: "partial_path", locals: {bar: params[:baz] 
  })}
end

it causes a double render conflict with render_wizard. I've tried doing an if/else statement like this:

if step == :times
  respond_to do |format|
    format.turbo_stream { render turbo_stream: turbo_stream.replace("foo", partial: "partial_path", locals: {bar: params[:baz] } )}
    format.html { times_path }
  end
else
    render_wizard
end

Which doesn't render the step at all. I haven't been able to find much information that connects wicked and turbostreams. I have many more steps other than just step_b that also use the render_wizard method, and was wondering if there's a way to accomplish this without a massive refactor?

per the docs I've seen (linked below), it states "You'll need to call render_wizard at the end of your action to get the correct views to show up." and if the turbo_stream view conflicts with render_wizard, it sounds like this might not be possible.

https://www.rubydoc.info/gems/wicked/1.3.4

all the examples I've seen using turbostream just tend to assume you have a very typical rails scaffold setup, where the "create" action maps to the create.turbo_stream.erb and the "delete" action maps to the delete.turbo_stream.erb, so it's hard to figure out exactly how to implement the same solutions if the controller looks different than those, as they do when using wicked wizard


EDIT:

See the comment below from Alex who was able to provide me with an answer for my issue. I just wanted to post a quick summary:

Somewhere in my step_b view, I have something similar to this -

step_b.html.erb:

<%= turbo_frame_tag "foo_frame" do %>
  <%= some_variable %>
<%= end %>

<%= link_to "step b", step_b_path(some_variable: "new value of some_variable"), data: { "turbo_stream": true } %>

As seen above, in the view for step_b you'll need a link with data-turbo-stream=true. This will cause the link click to be of type "text/vnd.turbo-stream.html", which is a typical turbo-stream request. Then when we later do respond_to do |format| that will tell rails to execute the format.turbo_stream code in your steps controller.

steps_controller.rb

def show
    respond_to do |format|
      case step
      when :step_a
        # dostuff
        
      when :step_b
        if request.referrer.include? wizard_url
          format.turbo_stream { render turbo_stream: turbo_stream.update("foo_frame", partial: path_to_partial, locals: { some_variable: params[:some_variable] }) }
        end
        
      when :step_c
        # dostuff
      
      format.html { render_wizard }
    end
end

For the issue I was running into, it seems that when navigating from step_a to step_b it's trying to process it as a turbostream and doesn't render the view for step_b. It may be because I have a nested turbostream in my case. However, I wanted to be able to target and replace a specific, nested turbostream.

The line if request.referrer.include? wizard_url basically just says "If the request is coming from the same step_b page, then perform this turbostream update on the "foo" turboframe. Therefore this code won't execute when transitioning from step_a to step_b, which resolves the issue described above

Thanks to Alex for all of his help, and providing a solution


Solution

  • I really feel like wicked just makes it a lot more confusing for you. You can just as easily use turbo frame with your existing controllers with whatever actions and responses you like.

    Here is what I've come up with wicked and some commented out regular controller alternatives:

    class OnboardingController < ApplicationController
      include Wicked::Wizard
    
      steps :one, :two, :complete
      # # or you can do it on your own
      # STEPS = ["one", "two", "complete"].freeze
    
      # GET wizard_path
      def show
        # NOTE: if you want to add turbo_stream responses here, respond_to
        #       block needs to wrap around the case statement, so that
        #       render_wizard can be wrapped as well.
        respond_to do |format|
          # case params[:id].to_sym
          case step
          when :one
            # NOTE: it's better to have a default value when params[:date] is empty
            #       on initial request.
            #       add links in step :one template with different date params
            #       when you click them, just let the page render again, there is
            #       no need to do anything else.
            @user = current_user
            format.turbo_stream { render turbo_stream: turbo_stream.update("stream_target", "step one content") }
          end
          format.html { render_wizard }
        end
    
        # # if you just replace `render_wizard` with you own simple logic, you
        # # won't need wicked wizard and won't have to fight it
        # respond_to do |format|
        #   format.html { render params[:id].presence_in(STEPS) || STEPS.first }
        # end
      end
    
      # PUT wizard_path
      def update
        case step
        when :one
          @user = current_user
          skip_step if @user.save
        end
        render_wizard
        # # or let render_wizard save it for you and go to the next step
        # render_wizard @user
    
        # # or do it yourself and turn it into a regular controller
        # respond_to do |format|
        #   if @user.save
        #     next_step = STEPS[STEPS.index(params[:id]).next]
        #     format.html { render next_step }
        #   else
        #     format.html { render params[:id] }
        #   end
        # end
      end
    
      # # and make your own helpers
      # private
      # def step
      #   params[:id].to_sym
      # end
      # helper_method :step
    end
    

    You can add a partial layout, so you don't have to repeat things between steps:

    # app/views/onboarding/_wizard_layout.html.erb
    
    <%# NOTE: if you want the url to update as well     vvvvvvv %>
    <%= turbo_frame_tag "wizard", data: {turbo_action: :advance} do %>
      <div class="flex items-center mb-4 gap-4">
        <%= link_to "< back", previous_wizard_path, class: "hover:text-blue-500" %>
        <h1 class="text-2xl font-bold">Step <%= step %></h1>
      </div>
      <%= yield %>
    <% end %>
    
    # app/views/onboarding/one.html.erb
    
    <%= render layout: "wizard_layout" do %>
      <%= turbo_frame_tag "time_selector" do %>
    
        <%= tag.div class: "flex gap-4" do %>
          <% date = Date.parse(params[:date] || Date.today.to_s) %>
          <%# NOTE: link to the current step with different params.
            #       you have to pass `params[:id]` so you don't override the current
            #       step name. %>
          <%= link_to "prev day", wizard_path(params[:id], {date: date.prev_day}), class: "text-blue-500" %>
          <%= link_to "today",    wizard_path(params[:id], {date: Date.today}),    class: "text-blue-500" %>
          <%= link_to "next day", wizard_path(params[:id], {date: date.next_day}), class: "text-blue-500" %>
        <% end %>
        <%= params[:date] %>
    
        <%# NOTE: just an example of how stream response would work
          #       because it is in a `show` action, it has to be a GET
          #       request. to make a GET turbo stream request you have to
          #       set `data-turbo-stream="true"` attribute %>
        <%= tag.div id: "stream_target" %>
        <%= button_to "a stream action", wizard_path, method: :get, data: {turbo_stream: true}, class: "bg-gray-100 px-2 py-1" %>
    
        <%# NOTE: put your form here, use outer frame as the target
          #       otherwise, you'll be stuck in a `time_selector` frame %>
        <%= form_with model: @user, url: wizard_path, method: :put, data: {turbo_frame: :wizard} do |f| %>
          <%= f.submit "Next button", class: "font-bold"  %>
        <% end %>
    
      <% end %>
    <% end %>
    

    Update

    <button> submits the form that it is nested in, that's just html. button_to is a rails helper that makes a form with a button to make POST/PUT/PATCH/DELETE requests, use it outside of forms.

    The issue is that everything is smooshed together in one action. When you submit the form it sends a TURBO_STREAM request, when you redirect turbo sends another TURBO_STREAM request to redirected url (which is show action). If you have format.turbo_stream that's the response you will get, otherwise, format.html is used.

    I mean, just another reason to ditch the wizard, or at least add some new actions for turbo_stream requests. But you can work around it:

    def update
      # ...
    
      # NOTE: redirect with .html extension so that `show` response
      #       would be html instead of turbo_stream
      render_wizard @user, {}, format: :html
    end
    

    or

    def show
      respond_to do |format|
        case step
        when :one
          @user = current_user
          format.turbo_stream { render turbo_stream: turbo_stream.update("stream_target", "step one content") }
        when :two
          # NOTE: only accept turbo_stream requests from the current
          #       step. that means when you redirect there is no
          #       turbo_stream format and html format will be used instead
          if request.referrer == wizard_url
            format.turbo_stream { render turbo_stream: turbo_stream.update("stream_target", "step two content") }
          end
        end
        format.html { render_wizard }
      end
    end
    

    This might help explain this further: https://stackoverflow.com/a/75657122/207090