hellion
hellion

Reputation: 4840

How to insert a form for a new record using Turbo/Stimuls?

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.

Upvotes: 2

Views: 1560

Answers (1)

yungindigo
yungindigo

Reputation: 281

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.

Upvotes: 2

Related Questions