2

The future of Rails seems to be moving away from UJS and towards Turbo and Stimulus. But, some features seem to require more code and more work vs old-school UJS.

For example: To insert a form inline that would allow the creation of a new record you could create a link like:

link_to 'add record', new_user_path, remote: true

then, in the controller:

def new
  @user = User.new
  respond_to do |format|
     format.js
  end
end

and, finally a new.js.erb view containing the content (form) to be executed in response to the new action.

One would think this would be simple to convert to Turbo simply by responding to:

def new
  @user = User.new
  respond_to do |format|
     format.turbo_stream
  end
end

and then change the new.js.erb to new.turbo_stream.erb with content like:

<turbo-stream action='append' target="<%= dom_id @user %>_new_form">
  <template>
      ...the user form stuff...
  </template>
</turbo-stream>

However, Turbo Streams do not handle GET requests. So, this approach does not work.

My question is: What is the Rails 7 way of handling this? I don't think UJS is the answer, since Turbo and Stimulus are "superseding" UJS functionality. Perhaps, the answer is to insert the new form using Stimulus, then use a stream to insert the subsequent new record following the POST request when the form is successful in the create action. But, this seems like so much more work than UJS is/was. It makes me think there's gotta be an easier, more fluid, less code way to handle this.

hellion
  • 4,602
  • 6
  • 38
  • 77

1 Answers1

2

For this I would use turbo-frames :

  • First make an empty turbo-frame called new_record

  • Then you can have a link and set the data-turbo-frame="new_record"

    this will act as if you clicked the link inside of the new_record turbo-frame

  • Then on the new template have a matching turbo-frame wrap your form and then

  • When you click on the new record button it will put the new record form in the spot I would say this is the hotwire way of doing it.

cursorrux
  • 1,382
  • 4
  • 9
  • 20
yungindigo
  • 241
  • 1
  • 6
  • 2
    This isn't a complete answer but is almost there! and led me to come up with the proper answer to this question which I'm also having. If you want to add multiple records, you need to manage a unique id per record while they are not persisted which can easily be passed around like: `data-turbo-frame="new_record_#{params.fetch(:index) + 1}"` – Peter P. Apr 20 '22 at 02:32