Problems using a create form multiple times

I have a standard CRUD operation on an Event model that I’m trying to create with Rails/Turbo, but running into issues with the create form. I need to perform two actions after create, so using Streams. One of the actions is to remove the form, which is in its own frame. The other action is to update the list of Event records.

Here’s what I have (I use slim, not ERB):

app/views/events/index.html.slim:

=> link_to 'Add Event', new_admin_event_path, data: { turbo_frame: 'event_form' }

= turbo_frame_tag 'event_form'

= turbo_frame_tag 'events_list' do
  == render 'list'

app/controllers/events_controller.rb:

  def create
    @event = Event.new(event_params)
    if @event.save
      respond_to do |format|
        format.html { redirect_to admin_events_url }
        format.turbo_stream
      end
    end
  end

app/views/events/create.turbo_stream.slim:

= turbo_stream.update 'event_form', '' # this is what seems to be the trouble?
= turbo_stream.update 'events_list', Event.all

The issue is that I can’t make the create form work more than once. It’ll create the record, and the turbo_stream file will correctly remove the form, but once that happens the ‘Add Event’ button will no longer work - it won’t populate the event_form frame again. Or put another way, I can’t add multiple Events without refreshing the page. What am I missing here?

I ended up working around it with the following in the turob_stream view:

= turbo_stream.replace 'event_form', turbo_frame_tag('event_form')

Hope it helps someone else. Would appreciate if anyone finds a better way.

Here’s the cycle of the turbo-frame

INITIAL:

<turbo-frame id='event_form'></tubo-frame>

ADD EVENT LINK:

<turbo-frame id='event_form' src="/admin/new">
  <form...>
</tubo-frame>

FORM SUBMIT:

<turbo-frame id='event_form' src="/admin/new"></tubo-frame>

When clicking on the link again, it tells the turbo-frame to update it’s GET src="/admin/new". It ignores the request since the src contains the same value in the turbo-frame already. I personally appreciate and leverage the caching strategy, but other hate it and submitted multiple bugs asking for a change.

You’re approach to reset the turbo-frame using turbo-stream replace is one way. The other method I’m familiar with uses a stimulus controller, but in this scenario I’d go with your solution.

1 Like

Thanks for replying. I could see that was going on in the inspector of the browser, but took a while for me to figure out a way around it. I also experimented a lot with using stimulus to make things work, but it seemed pretty complicated for what should be a simple thing.