How can I make this code behave similar to `link_to` with `remote: true`?

I’m trying to get this code to work similarly to link_to ... remote: true, where I can hit a URL which returns JavaScript, and then the client runs it. It doesn’t seem like my code will work, because Turbolinks.visit doesn’t seem to support that paradigm.

Any suggestions on how I might re-work this? Thanks.

<%= form_with(model: rig_return, url: '#') do |f| %>
  <%= f.select(
    :action,
    options_for_select(["View Details"]),
    {include_blank: false},
    {
      onchange: "javascript: perform_action(this, #{rig_return.id})",
      onfocus: "this.selectedIndex = -1",
      class: "form-control"
    }
  ) %>
<% end %>

<script>
  function perform_action(target, rig_return_id) {
    let url = null

    switch(target.value) {
      case 'View Details':
        url = `/inv_procure/rig_returns/${rig_return_id}.js`
        break;
    }

    Turbolinks.visit(url)
  }
</script>

If you still have Turbolinks (not Turbo) and UJS, you could try building a link in the DOM and giving it a click(). Or better, a Rails.fire('click').

Walter

1 Like

I ended up using StimulusJS.

In my StimulusJS controller I’m using Rails.ajax({... dataType: 'script'}).

This solution seems a lot cleaner. :stuck_out_tongue: